/*** Created by yun on 2017/12/7.*/
//local
// var Url='https://localhost:8009/';
// var preUrl='https://test.skylarkai.cn/';
//dev
var Url='https://test.skylarkai.cn:8009/';
var preUrl='https://test.skylarkai.cn/';
//prod
// var Url='https://800fuwu.cn:8009/';
// var preUrl='https://800fuwu.cn/';


var token;
var cjglyflg=0;
var sizepercentage;
var sizestorage;
var sizetotal;
var app = angular.module('wcmApp', ['ng','ngAnimate','oc.lazyLoad', 'ui.router', 'ui.router.state.events','ephox.textboxio','ngStorage']);
//配置跨域请求
app.config(function($httpProvider){
    $httpProvider.defaults.headers.post = {
        'Content-Type': 'application/x-www-form-urlencoded',
        'Access-Control-Allow-Origin':'*',
        'Access-Control-Allow-Methods':'POST'
    };
    $httpProvider.defaults.transformRequest= function(obj) {
        var str = [];
        for(var p in obj){
            str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));
        }
        return str.join("&");
    };

    $httpProvider.interceptors.push('httpInterceptor');
});
//配置路由
app.config(function($stateProvider, $urlRouterProvider,$locationProvider)
{
    $urlRouterProvider.otherwise('login');
    $stateProvider
        .state('login', {
            cache:false,
            url: '/login',
            templateUrl: 'web/login/login.html',
            controller: 'loginCtrl'
        })
        .state('users', {
            cache:false,
            url: '/users',
            templateUrl: '/web/user/user.html',
            controller: 'userCtrl'
        })
        .state('filemanager', {
            cache:false,
            url: '/filemanager',
            templateUrl: '/web/allfile/allfile.html',
            controller: 'all_fileCtrl'
        })
        .state('pagemanager', {
            cache:false,
            url: '/pagemanager',
            templateUrl: '/web/pagemanagement/pagemanagement.html',
            controller: 'pagemanagementCtrl'
        })
        .state('video', {
            cache:false,
            url: '/video',
            templateUrl: '/web/video/video.html',
            controller: 'videoCtrl'
        })
        .state('roles', {
            cache:false,
            url: '/roles',
            templateUrl: '/web/role/role.html',
            controller: 'roleCtrl'
        })
        .state('resources', {
            cache:false,
            url: '/resources',
            templateUrl: '/web/resources/resources.html',
            controller: 'resourcesCtrl'
        })
        .state('tenans', {
            cache:false,
            url: '/tenans',
            templateUrl: '/web/tenan/tenan.html',
            controller: 'tenanCtrl'
        })
        .state('recycle', {
            cache:false,
            url: '/recycle',
            templateUrl: '/web/recycle/recycle.html',
            controller: 'recycleCtrl'
        })
        .state('userinfo', {
            cache:false,
            url: '/userinfo',
            templateUrl: '/web/personinfo/personinfo.html',
            controller: 'personinfoCtrl'
        })
        .state('userpwd', {
            cache:false,
            url: '/userpwd',
            templateUrl: '/web/changepwd/changepwd.html',
            controller: 'changepwdCtrl'
        })
        .state('403', {
            cache:false,
            url: '/403',
            templateUrl: '403.html'
        });
    $locationProvider.html5Mode(true);
});
//主控制器
app.controller('parentCtrl', function ($scope, $location,$state,$sessionStorage,$http) {
    $scope.go = function(state) {
        $state.go(state);
    };
    var user = angular.fromJson($sessionStorage.USER)
    $scope.user=user;
    //弹框的设置
    toastr.options = {
        closeButton: false,
        debug: false,
        progressBar: false,
        positionClass: "toast-top-center",
        autoDismiss: true,//显示最新的toastr
        onclick: null,
        showDuration: "300",
        hideDuration: "1000",
        timeOut: "2000",
        extendedTimeOut: "1000",
        showEasing: "swing",
        hideEasing: "linear",
        showMethod: "fadeIn",
        hideMethod: "fadeOut",
        preventDuplicates:"false",//重复内容的提示框只出现一次，无论提示框是打开还是关闭
        preventManyTimes:"true",
        preventOpenDuplicates: true,// 重复内容的提示框在开启时只出现一个 如果当前的提示框已经打开，不会多开。直到提示框关闭后，才可再开)
        maxOpened:2,// 页面一次性最多显示多少个toastr.
        newestOnTop: true //新的toastr会显示在旧的toastr前面
    };
    //关闭模态框清空数据
    $scope.close=function(){
        $(".modal").modal('hide');
        $(".dz-preview").remove();

    };
    //退出登录
    $scope.exit=function() {
        var user = angular.fromJson($sessionStorage.USER);
        user = {};
        $http( {
            method: 'post',
            url:Url+'logout',
            withCredentials:true,
            headers:{
                Authorization:token
            }
        });
        $sessionStorage.TOKEN="";
        token="";
        cjglyflg=0;
        $scope.go('login');
    };
});
//文档中的控制器
app.controller('all_fileCtrl', function ($http, $rootScope,$scope,$compile,getTime,$state,$sessionStorage,$ocLazyLoad,$window,getStorage) {
    //保存用户的基本信息
    var user = angular.fromJson($sessionStorage.USER);
    $scope.user=user;
    var flag=$sessionStorage.CJGLYFLG;
    //加载表格
    $scope.loadTable=function(){
        $.fn.dataTable.ext.errMode = 'none';
        $('#allfileTable').dataTable({
            "destroy": true,
            "searching": true,
            "bAutoWidth": true, //是否自适应宽度
            "sPaginationType": "full_numbers",
            "serverSide": true,//开启服务器模式，使用服务器端处理配置datatable
            //"processing": true,//开启读取服务器数据时显示正在加载中……特别是大数据量的时候，开启此功能比较好
            "bPaginage": true,
            "bDeferRender":true,
            "ordering": false, // 禁止排序
            "bFilter" : true, //是否启动过滤、搜索功能
            "language": {
                "sProcessing": "加载中...",
                "sLengthMenu": "显示 _MENU_ 项结果",
                "sZeroRecords": "没有匹配结果",
                "sInfo": "显示第 _START_ 至 _END_ 项结果，共 _TOTAL_ 项",
                "sInfoEmpty": "显示第 0 至 0 项结果，共 0 项",
                "sInfoFiltered": "(由 _MAX_ 项结果过滤)",
                "sInfoPostFix": "",
                "sSearch": "过滤:",
                "sEmptyTable": "表中数据为空",
                "sLoadingRecords": "载入中...",
                "sInfoThousands": ",",
                "oPaginate": {
                    "sFirst": "首页",
                    "sPrevious": "上页",
                    "sNext": "下页",
                    "sLast": "末页"
                },
                "oAria": {
                    "sSortAscending": ": 以升序排列此列",
                    "sSortDescending": ": 以降序排列此列"
                }
            },
            "fnPreDrawCallback": function( oSettings ) {
                $('.dataTables_filter input').attr({'name':'search','placeholder': '请输入文件名称'});//提示
            },
            "ajax":{
                "url":Url+'filemanager/selectInitFileListByParameter?tenanid='+user.tenanid+'&userid='+user.userid+'&flag='+flag+'',
                "headers":{
                    "Authorization":token
                },
                "xhrFields": {
                    "withCredentials": true
                },
                error: function(){
                    $state.go("403");
                }
            },
            "columns": [
                {"data": "suffix"},
                {"data": "size"},
                {"data":"updatetime"},
                {"data": "suffix"}
            ],
            "columnDefs": [
                {
                    "render": function (data, type, row) {
                        if (data == "") {
                            return '<input type="checkbox" value="'+ row.id +'" /><span class="file-icon"></span><a href="javascript:void(0)" ng-click="fileDetail('+row.id+')" zg-access="filemanager/selectByPageFolder">'+row.filename+'</a>';
                        } else if(data == "doc"){
                            return '<input type="checkbox" value="'+ row.id +'" /><span class="doc-icon"></span><a href="#">'+row.filename+'.doc</a>';
                        } else if(data == "docx"){
                            return '<input type="checkbox" value="'+ row.id +'" /><span class="doc-icon"></span><a href="#">'+row.filename+'.docx</a>';
                        } else if(data == "pdf"){
                            return '<input type="checkbox" value="'+ row.id +'" /><span class="pdf-icon"></span><a href="#">'+row.filename+'.pdf</a>';
                        }
                    },"fnCreatedCell": function (nTd, sData, oData, iRow, iCol) {
                    $compile(nTd)($scope);
                },
                    "targets": 0
                },
                {
                    "render":function(data, type, row){
                        //if(data==0&&row.suffix==""){
                        //    return '';
                        //}else if(data<10.3){
                        //    var size=parseInt(data);
                        //    size = size.toFixed(2);
                        //    return ''+size+'B';
                        //}else if(data<1048576){
                        //    var size=parseInt(data)/1024;
                        //    size = size.toFixed(2);
                        //    return ''+size+'KB';
                        //}else{
                        //    var size=parseInt(data)/1024/1024;
                        //    size = size.toFixed(2);
                        //    return ''+size+'MB'
                        //}
                        if(data==0&&row.suffix==""){
                            return '';
                        }else{
                            return getTime.bytesToSize(data);
                        }
                    },
                    "targets":1
                },
                {
                    "render":function(data, type, row){
                        return getTime.getLocalTime(data);
                    },
                    "targets":2
                },
                {
                    "render": function (data, type, row) {
                        if (data == "") {
                            return ' <button type="button" class="btn btn-danger" ng-click="delete('+row.id+')" zg-access="filemanager/delete">删除</button>';
                        } else if(data == "doc"||data == "docx"){
                            return ' <button type="button" class="btn btn-danger" ng-click="delete('+row.id+')" zg-access="filemanager/delete">删除</button> <button type="button" class="btn btn-success" zg-access="filemanager/convertFile" ng-click="convertFile('+row.id+')">转换</button>';
                        } else if(data == "pdf"){
                            return ' <button type="button" class="btn btn-danger" ng-click="delete('+row.id+')" zg-access="filemanager/delete">删除</button> <button type="button" class="btn btn-success" zg-access="filemanager/convertFile" ng-click="convertFile('+row.id+')">转换</button>';
                        }else if(data ==  "html"){
                            return '<button type="button" class="btn btn-danger" ng-click="delete('+row.id+')" zg-access="filemanager/delete">删除</button>';
                        }else if(data ==  "txt"){
                            return '<button type="button" class="btn btn-danger" ng-click="delete('+row.id+')" zg-access="filemanager/delete">删除</button>';
                        }else if(data ==  "mp4"){
                            return '<button type="button" class="btn btn-danger" ng-click="delete('+row.id+')" zg-access="filemanager/delete">删除</button>';
                        }
                    },"fnCreatedCell": function (nTd, sData, oData, iRow, iCol) {
                    $compile(nTd)($scope);
                },
                    "targets": 3
                },
            ],
        });
    };
    $(document).ready(function(){
        $scope.loadTable();
        if(angular.isUndefined($scope.fatherid)){
            $scope.fatherid="";
        }
        $("#bread-crumbs").empty();
        var html='<li><a href="javascript:void(0)" >全部文件</a></li>';
        $("#bread-crumbs").append(html);
        getStorage.newStorage();
    });
    //文件夹详情
    $scope.fileDetail=function(id){
        $.fn.dataTable.ext.errMode = 'none';
        $('#allfileTable').dataTable({
            "destroy": true,
            "searching": true,
            "bAutoWidth": true, //是否自适应宽度
            "sPaginationType": "full_numbers",
            "serverSide": true,//开启服务器模式，使用服务器端处理配置datatable
            //"processing": true,//开启读取服务器数据时显示正在加载中……特别是大数据量的时候，开启此功能比较好
            "bPaginage": true,
            "bDeferRender":true,
            "ordering": false, // 禁止排序
            "bFilter" : true, //是否启动过滤、搜索功能
            "language": {
                "sProcessing": "加载中...",
                "sLengthMenu": "显示 _MENU_ 项结果",
                "sZeroRecords": "没有匹配结果",
                "sInfo": "显示第 _START_ 至 _END_ 项结果，共 _TOTAL_ 项",
                "sInfoEmpty": "显示第 0 至 0 项结果，共 0 项",
                "sInfoFiltered": "(由 _MAX_ 项结果过滤)",
                "sInfoPostFix": "",
                "sSearch": "过滤:",
                "sEmptyTable": "表中数据为空",
                "sLoadingRecords": "载入中...",
                "sInfoThousands": ",",
                "oPaginate": {
                    "sFirst": "首页",
                    "sPrevious": "上页",
                    "sNext": "下页",
                    "sLast": "末页"
                },
                "oAria": {
                    "sSortAscending": ": 以升序排列此列",
                    "sSortDescending": ": 以降序排列此列"
                }
            },
            "fnPreDrawCallback": function( oSettings ) {
                $('.dataTables_filter input').attr({'name':'search','placeholder': '请输入文件名称'});//提示
            },
            "ajax":{
                "url":Url+'filemanager/selectByPageFolder?id='+id+'&flag='+flag+'',
                "headers":{
                    "Authorization":token
                },
                "xhrFields": {
                    "withCredentials": true
                },
                error: function(){
                    $state.go("403");
                }
            },
            "columns": [
                {"data": "suffix"},
                {"data": "size"},
                {"data": "updatetime"},
                {"data": "suffix"}
            ],
            "columnDefs": [
                {
                    "render": function (data, type, row) {
                        if (data == "") {
                            return '<input type="checkbox" value="'+ row.id +'" /><span class="file-icon"></span><a href="javascript:void(0)" ng-click="fileDetail('+row.id+')">'+row.filename+'</a>';
                            //return '<input type="checkbox" value="'+ row.id +'" /><span class="file-icon"></span><a href="/recycle/filedetail.html?id='+row.id+'">'+row.filename+'</a>';
                        } else if(data == "doc"){
                            return '<input type="checkbox" value="'+ row.id +'" /><span class="doc-icon"></span><a href="#">'+row.filename+'.doc</a>';
                        } else if(data == "docx"){
                            return '<input type="checkbox" value="'+ row.id +'" /><span class="doc-icon"></span><a href="#">'+row.filename+'.docx</a>';
                        } else if(data == "pdf"){
                            return '<input type="checkbox" value="'+ row.id +'" /><span class="pdf-icon"></span><a href="#">'+row.filename+'.pdf</a>';
                        }else if(data ==  "html"){
                            return '<input type="checkbox" value="'+ row.id +'" /><span class="html-icon"></span><a href="#">'+row.filename+'.html</a>';
                        }else if(data ==  "txt"){
                            return '<input type="checkbox" value="'+ row.id +'" /><span class="doc-icon"></span><a href="#">'+row.filename+'.txt</a>';
                        }else if(data ==  "mp4"){
                            return '<input type="checkbox" value="'+ row.id +'" /><span class="doc-icon"></span><a href="#">'+row.filename+'.mp4</a>';
                        }
                    },"fnCreatedCell": function (nTd, sData, oData, iRow, iCol) {
                    $compile(nTd)($scope);
                },
                    "targets": 0
                },
                {
                    "render":function(data, type, row){
                        if(data==0&&row.suffix==""){
                            return '';
                        }else{
                            return getTime.bytesToSize(data);
                        }
                    },
                    "targets":1
                },
                {
                    "render":function(data, type, row){
                        return getTime.getLocalTime(data);
                    },
                    "targets":2
                },
                {
                    "render": function (data, type, row) {
                        if (data == "") {
                            return ' <button type="button" class="btn btn-danger" ng-click="delete('+row.id+')" zg-access="filemanager/delete">删除</button>';
                        } else if(data == "doc"||data == "docx"){
                            return ' <button type="button" class="btn btn-danger" ng-click="delete('+row.id+')" zg-access="filemanager/delete">删除</button> <button type="button" class="btn btn-success" zg-access="filemanager/convertFile" ng-click="convertFile('+row.id+')">转换</button>';
                        } else if(data == "pdf"){
                            return ' <button type="button" class="btn btn-danger" ng-click="delete('+row.id+')" zg-access="filemanager/delete">删除</button> <button type="button" class="btn btn-success" zg-access="filemanager/convertFile" ng-click="convertFile('+row.id+')">转换</button>';
                        }else if(data ==  "html"){
                            return '<button type="button" class="btn btn-danger" ng-click="delete('+row.id+')" zg-access="filemanager/delete">删除</button>';
                        }else if(data ==  "txt"){
                            return '<button type="button" class="btn btn-danger" ng-click="delete('+row.id+')" zg-access="filemanager/delete">删除</button>';
                        }else if(data ==  "mp4"){
                            return '<button type="button" class="btn btn-danger" ng-click="delete('+row.id+')" zg-access="filemanager/delete">删除</button>';
                        }
                    },"fnCreatedCell": function (nTd, sData, oData, iRow, iCol) {
                    $compile(nTd)($scope);
                },
                    "targets": 3
                },
            ],
        });
        //面包屑展示
        $http({
            method: 'post',
            url:Url+'filemanager/selectByPageFolder?id='+id+'',
            withCredentials:true,
            headers:{
                Authorization:token
            },
            data:{id:id}
        }).then(function successCallback(response) {
            if(response.data.flg==0){
                $scope.fatherid=id;
                //面包屑
                $("#bread-crumbs").empty();
                var compileFn = $compile('<li><a href="javascript:void(0);" ng-click="backoff('+id+')" zg-access="filemanager/backoff" class="front">返回上一页</a><span>|</span></li><li><span>全部文件</span><span >'+response.data.localpath+'</span></li>');
                var $dom = compileFn($scope);
                $("#bread-crumbs").append($dom);
            }else{
                toastr.error(response.data.message);
            }
        },function errorCallback(response){
            // console.log(response.data)
        });

    };
    //批量删除
    $scope.deleteBatch=function(){
        var ipts = $(":checkbox:checked");
        var arr=[];
        ipts.each(function(){
            arr.push($(this).val());
        });
        if(arr.length<1){
            toastr.warning("请选择一个数据")
        }else{
            $("#deleteSure").modal("show");
            $scope.sureDelete=function(){
                $http( {
                    method: 'post',
                    url:Url+'filemanager/batchDelete',
                    withCredentials:true,
                    headers:{
                        Authorization:token
                    },
                    data:{ids:arr}
                }).then(function successCallback(response) {
                    if(response.data.code==0){
                        toastr.success(response.data.message);
                        if($scope.fatherid){
                            $scope.fileDetail($scope.fatherid);
                        }else{
                            $scope.loadTable();
                        }
                        getStorage.newStorage();
                        $("#deleteSure").modal("hide");
                    }else{
                        toastr.error(response.data.message);
                        $("#deleteSure").modal("hide");
                    }
                },function errorCallback(response){
                    toastr.error(response.data.message);
                });
            }
        }
    };
    //删除单个文件
    $scope.delete=function(id){
        $("#deleteSure").modal("show");
        $scope.sureDelete=function(){
            $http( {
                method: 'post',
                url:Url+'filemanager/delete',
                withCredentials:true,
                headers:{
                    Authorization:token
                },
                data:{id:id}
            }).then(function successCallback(response) {
                if(response.data.code==0){
                    toastr.success(response.data.message);
                    if($scope.fatherid){
                        $scope.fileDetail($scope.fatherid);
                    }else{
                        $scope.loadTable();
                    }
                    getStorage.newStorage();
                    $("#deleteSure").modal("hide");
                }else{
                    toastr.error(response.data.message);
                    $("#deleteSure").modal("hide");
                }
            },function errorCallback(response){
                // console.log(response.data)
            });
        }
    };

    //文件上传
    Dropzone.options.myAwesomeDropzone = false;
    Dropzone.autoDiscover = false;
    $scope.openUpload=function(){
        $("#uploadFile").modal("show");
        $scope.filepath ="";
        var myDropzone = new Dropzone("#dropzoneFile", {
            url:Url+'filemanager/upload?tenanid='+user.tenanid+'&userid='+user.userid+'',
            withCredentials:true,
            headers:{
                Authorization:token
            },
            method:"post",  //也可用put
            paramName:"uploadfile", //默认为file
            maxThumbnailFilesize: 20,
            parallelUploads: 100,
            maxFiles:10,
            maxFilesize: 20,//单位为MB
            autoProcessQueue: false,
            uploadMultiple:true,
            hiddenInputContainer:true,
            acceptedFiles: ".doc,.docx,.pdf", //上传的类型
            addRemoveLinks:true,
            dictDefaultMessage:'拖动文件至此或者点击上传',
            dictMaxFilesExceeded: "您最多只能上传10个文件！",
            dictResponseError: '文件上传失败!',
            dictInvalidFileType: "文件类型只能是*.doc,*.docx,*.pdf。",
            dictFallbackMessage:"浏览器不受支持",
            dictFileTooBig:"文件过大上传文件最大支持.",
            dictRemoveFile: "删除",
            dictCancelUpload: "取消",
            init:function(){
                this.on("addedfile", function(file) {
                    //上传文件时触发的事件
                    document.querySelector('div .dz-default').style.display = 'none';
                    $scope.file = file;
                    $scope.filepath = file.fullPath + "|" + $scope.filepath;
                    $scope.$apply(function() {
                        $scope.fileAdded = true;
                    });
                });
                this.on("sending",function (file, xhr, formData) {
                    formData.append("filepath", $scope.filepath);
                    console.log( $scope.filepath)
                    formData.append("fatherid", $scope.fatherid);
                });
                this.on("success",function(file,response){
                    //上传成功触发的事件
                    $scope.filepath ="";
                    if(response.code==0){
                        toastr.success("上传成功");
                        $("#uploadFile").modal("hide");
                        if($scope.fatherid){
                            $scope.fileDetail($scope.fatherid);
                        }else{
                            $scope.loadTable();
                        }
                        myDropzone.removeAllFiles();
                        getStorage.newStorage();
                    }else{
                        $("#uploadFile").modal("hide");
                        toastr.error(response.message);
                        myDropzone.removeAllFiles();
                    }
                });
                this.on("error",function (file,response) {
                    //上传失败触发的事件
                    //console.log(response);
                    if(response.code!==0){
                        toastr.error(response);
                    }
                });
                this.on("maxfilesreached",function(){
                   toastr.warning("文件数量超过最大件数！");
                });
                this.on("removedfile",function(file){
                    var para;
                    if("undefined" == new String(file.fullPath)) {
                        //para = file.name;
                        para = file.fullPath;
                    } else {
                        para = file.fullPath;
                    }
                    $scope.filepath= $scope.filepath.replace(para+"|","");
                    document.querySelector('div .dz-default').style.display = 'block';
                });
            }
        });
        $scope.uploadFile = function() {
            myDropzone.processQueue();
        };
        $scope.reset = function() {
            myDropzone.removeAllFiles();
        };
    };

    //转换文件
    $scope.convertFile=function(id){
        $http( {
            method: 'post',
            url:Url+'filemanager/convertFile',
            withCredentials:true,
            headers:{
                Authorization:token
            },
            data:{id:id}
        }).then(function successCallback(response) {
            $("#deleteSure").modal("hide");
            if(response.data.code==0){
                toastr.success(response.data.message);
                if($scope.fatherid){
                    $scope.fileDetail($scope.fatherid);
                }else{
                    $scope.loadTable();
                }
                getStorage.newStorage();
            }else{
                toastr.error(response.data.message);

            }
        },function errorCallback(response){
            // console.log(response.data)
        });
    };
    //新建文件夹
    $scope.newFolder=function(){
        var compileFn = $compile('<tr class="odd gradeX"><td><input type="checkbox" value="1"><span class="file-icon"></span> <input type="text" class="form-control" placeholder="新建文件夹" style="width:50%;display:inline-block" id="newfolder" ng-model="filename" minlength="1" maxlength="50"> <span class="glyphicon glyphicon-ok" ng-click="saveFolder()" zg-access="filemanager/saveFolder"></span> <span class="glyphicon glyphicon-remove" ng-click="closeFolder()"></span></td><td></td><td></td><td></td></tr>');
        var $dom = compileFn($scope);
        $("table tr:eq(0)").after($dom);
        //确定新建文件夹
        $scope.saveFolder=function(){
            var name=$scope.filename;
            if(name == undefined || name == null || name==""){
                return toastr.error('文件名不能为空');
            }
            $http({
                method: 'post',
                url:Url+'filemanager/saveFolder',
                withCredentials:true,
                headers:{
                    Authorization:token
                },
                data:{filename:name,userid:user.userid,tenanid:user.tenanid,fatherid:$scope.fatherid}
            }).then(function successCallback(response) {
                if(response.data.code==0){
                    toastr.success(response.data.message);
                    if($scope.fatherid){
                        $scope.fileDetail($scope.fatherid);
                    }else{
                        $scope.loadTable();
                    }
                    $scope.filename="";
                    $scope.closeFolder();
                }else{
                    toastr.error(response.data.message);
                }
            },function errorCallback(response){
                toastr.error(response.data.message);
            });
        }
    };
    //取消新建文件夹
    $scope.closeFolder=function(){
        $('table tr:eq(1)').remove();
        $scope.filename="";
    };
    //返回上一级目录
    $scope.backoff=function(id){
        $http({
            method: 'post',
            url:Url+'filemanager/backoff',
            withCredentials:true,
            headers:{
                Authorization:token
            },
            data:{id:id,flag:flag}
        }).then(function successCallback(response) {
            if(response.data.code==0){
                $.fn.dataTable.ext.errMode = 'none';
	            $("#allfileTable").empty();
		        $('#allfileTable').dataTable({
		            "destroy": true,
                    "searching": true,
                    "bAutoWidth": true, //是否自适应宽度
                    "sPaginationType": "full_numbers",
                    "serverSide": true,//开启服务器模式，使用服务器端处理配置datatable
                    "bPaginage": true,
                    "bDeferRender":true,
                    "ordering": false, // 禁止排序
                    "bFilter" : true, //是否启动过滤、搜索功能
                    "language": {
                        "sProcessing": "加载中...",
                        "sLengthMenu": "显示 _MENU_ 项结果",
                        "sZeroRecords": "没有匹配结果",
                        "sInfo": "显示第 _START_ 至 _END_ 项结果，共 _TOTAL_ 项",
                        "sInfoEmpty": "显示第 0 至 0 项结果，共 0 项",
                        "sInfoFiltered": "(由 _MAX_ 项结果过滤)",
                        "sInfoPostFix": "",
                        "sSearch": "过滤:",
                        "sEmptyTable": "表中数据为空",
                        "sLoadingRecords": "载入中...",
                        "sInfoThousands": ",",
                        "oPaginate": {
                            "sFirst": "首页",
                            "sPrevious": "上页",
                            "sNext": "下页",
                            "sLast": "末页"
                        },
                        "oAria": {
                            "sSortAscending": ": 以升序排列此列",
                            "sSortDescending": ": 以降序排列此列"
                        }
                    },
                    "fnPreDrawCallback": function( oSettings ) {
                        $('.dataTables_filter input').attr({'name':'search','placeholder': '请输入文件名称'});//提示
                    },
                    "ajax":{
                        "url":Url+'filemanager/backoff?id='+id+'&flag='+flag+'',
                        "headers":{
                            "Authorization":token
                        },
                        "xhrFields": {
                            "withCredentials": true
                        },
                        error: function(){
                            $state.go("403");
                        }
                    },
                    "columns": [
                        {"data": "suffix"},
                        {"data": "size"},
                        {"data": "updatetime"},
                        {"data": "suffix"}
                    ],
                    "columnDefs": [
                        {
                            "render": function (data, type, row) {
                                if (data == "") {
                                    return '<input type="checkbox" value="'+ row.id +'" /><span class="file-icon"></span><a href="javascript:void(0)" ng-click="fileDetail('+row.id+')" zg-access="pagemanager/getHtmlFolder">'+row.filename+'</a>';
                                } else if(data == "doc"){
                                    return '<input type="checkbox" value="'+ row.id +'" /><span class="doc-icon"></span><a href="#">'+row.filename+'.doc</a>';
                                } else if(data == "docx"){
                                    return '<input type="checkbox" value="'+ row.id +'" /><span class="doc-icon"></span><a href="#">'+row.filename+'.docx</a>';
                                } else if(data == "pdf"){
                                    return '<input type="checkbox" value="'+ row.id +'" /><span class="pdf-icon"></span><a href="#">'+row.filename+'.pdf</a>';
                                } else if(data == "html"){
                                    return '<input type="checkbox" value="'+ row.id +'" /><span class="html-icon"></span><a href="#">'+row.filename+'.html</a>';
                                }
                            },"fnCreatedCell": function (nTd, sData, oData, iRow, iCol) {
                            $compile(nTd)($scope);
                        },
                            "targets": 0
                        },
                        {
                            "render":function(data, type, row){
                                if(data==0&&row.suffix==""){
                                    return '';
                                }else{
                                    return getTime.bytesToSize(data);
                                }
                            },
                            "targets":1
                        },
                        {
                            "render":function(data, type, row){
                                return getTime.getLocalTime(data);
                            },
                            "targets":2
                        },
                        {
                            "render": function (data, type, row) {
                                if (data == "") {
                                    return ' <button type="button" class="btn btn-danger" ng-click="delete('+row.id+')" zg-access="pagemanager/deleteHtml">删除</button>';
                                    //return '<input type="checkbox" value="'+ row.id +'" /><span class="file-icon"></span><a href="/recycle/filedetail.html?id='+row.id+'">'+row.filename+'</a>';
                                } else if(data == "doc"||data == "docx"){
                                    return ' <button type="button" class="btn btn-danger" ng-click="delete('+row.id+')" zg-access="pagemanager/deleteHtml">删除</button> <button type="button" class="btn btn-success" zg-access="filemanager/convertFile" ng-click="convertFile('+row.id+')">转换</button>';
                                } else if(data == "pdf"){
                                    return ' <button type="button" class="btn btn-danger" ng-click="delete('+row.id+')" zg-access="pagemanager/deleteHtml">删除</button> <button type="button" class="btn btn-success" zg-access="filemanager/convertFile" ng-click="convertFile('+row.id+')">转换</button>';
                                }else if(data ==  "html"){
                                    return '<button type="button" class="btn btn-danger" ng-click="delete('+row.id+')" zg-access="pagemanager/deleteHtml">删除</button><button type="button" class="btn btn-success" ng-click="instantiateTextbox('+row.id+')" zg-access="pagemanager/getHtmlContent">编辑</button><button type="button" class="btn btn-info" ng-click="getcontent('+row.id+')" zg-access="pagemanager/previewHtml">浏览</button>';
                                }
                            },"fnCreatedCell": function (nTd, sData, oData, iRow, iCol) {
                            $compile(nTd)($scope);
                        },
                            "targets": 3
                        }
                    ]
                });
                if(response.data.id){
                    $scope.fatherid=response.data.id;
                    $("#bread-crumbs").empty();
                    var compileFn = $compile('<li><a href="javascript:void(0);" ng-click="backoff('+response.data.id+')" class="front">返回上一页</a><span>|</span></li><li><span>全部文件</span><span>'+response.data.localPath+'</span></li>');
                    var $dom = compileFn($scope);
                    $("#bread-crumbs").append($dom);
                }else{
                    $scope.fatherid="";
                    $("#bread-crumbs").empty();
                    var html='<li><a href="javascript:void(0)">全部文件</a></li>';
                    $("#bread-crumbs").append(html);
                }
            }else{
                toastr.error(response.data.message);
            }
        },function errorCallback(response){
            toastr.error(response.data.message);
        });
    }
});
//网页管理的控制器
app.controller('pagemanagementCtrl',function ($http, $scope,$window,$compile,getTime,$state,$sessionStorage,$ocLazyLoad,getStorage) {
    //延迟加载编辑器的js
    $ocLazyLoad.load('../../lib/angular-textbox.io-master/factories/tbioConfigFactory.js');
    $ocLazyLoad.load('../../lib/angular-textbox.io-master/factories/tbioValidationsFactory.js');
    $ocLazyLoad.load('../../lib/textboxio-client/textboxio/textboxio.js');
    //获取用户信息
    var user = angular.fromJson($sessionStorage.USER);
    $scope.user=user;
    var flag=$sessionStorage.CJGLYFLG;
    //表格展示
    $scope.loadTable=function(){
        $.fn.dataTable.ext.errMode = 'none';
        $('#page_managementTable').dataTable({
            "destroy": true,
            "searching": true,
            "bAutoWidth": true, //是否自适应宽度
            "sPaginationType": "full_numbers",
            "serverSide": true,//开启服务器模式，使用服务器端处理配置datatable
            //"processing": true,//开启读取服务器数据时显示正在加载中……特别是大数据量的时候，开启此功能比较好
            "bPaginage": true,
            "bDeferRender":true,
            "ordering": false, // 禁止排序
            "bFilter" : true, //是否启动过滤、搜索功能
            "language": {
                "sProcessing": "加载中...",
                "sLengthMenu": "显示 _MENU_ 项结果",
                "sZeroRecords": "没有匹配结果",
                "sInfo": "显示第 _START_ 至 _END_ 项结果，共 _TOTAL_ 项",
                "sInfoEmpty": "显示第 0 至 0 项结果，共 0 项",
                "sInfoFiltered": "(由 _MAX_ 项结果过滤)",
                "sInfoPostFix": "",
                "sSearch": "过滤:",
                "sEmptyTable": "表中数据为空",
                "sLoadingRecords": "载入中...",
                "sInfoThousands": ",",
                "oPaginate": {
                    "sFirst": "首页",
                    "sPrevious": "上页",
                    "sNext": "下页",
                    "sLast": "末页"
                },
                "oAria": {
                    "sSortAscending": ": 以升序排列此列",
                    "sSortDescending": ": 以降序排列此列"
                }
            },
            "fnPreDrawCallback": function( oSettings ) {
                $('.dataTables_filter input').attr({'name':'search','placeholder': '请输入文件名称'});//提示
            },
            "ajax":{
                "url":Url+'pagemanager/getHtmlFile?tenanid='+user.tenanid+'&userid='+user.userid+'&flag='+flag+'',
                "headers":{
                    "Authorization":token
                },
                "xhrFields": {
                    "withCredentials": true
                },
                error: function(){
                    $state.go("403");
                }
            },
            "columns": [
                {"data": "suffix"},
                {"data": "size"},
                {"data": "updatetime"},
                {"data": "suffix"},
            ],
            "columnDefs": [
                {
                    "render": function (data, type, row) {
                        if (data == "") {
                            return '<input type="checkbox" value="'+ row.id +'" /><span class="file-icon"></span><a href="javascript:void(0)" ng-click="fileDetail('+row.id+')" zg-access="pagemanager/getHtmlFolder">'+row.filename+'</a>';
                        } else if(data == "doc"){
                            return '<input type="checkbox" value="'+ row.id +'" /><span class="doc-icon"></span><a href="#">'+row.filename+'.doc</a>';
                        } else if(data == "docx"){
                            return '<input type="checkbox" value="'+ row.id +'" /><span class="doc-icon"></span><a href="#">'+row.filename+'.docx</a>';
                        } else if(data == "pdf"){
                            return '<input type="checkbox" value="'+ row.id +'" /><span class="pdf-icon"></span><a href="#">'+row.filename+'.pdf</a>';
                        } else if(data == "html"){
                            return '<input type="checkbox" value="'+ row.id +'" /><span class="html-icon"></span><a href="javascript:void(0)" ng-click="getcontent('+row.id+')">'+row.filename+'.html</a>';
                        }else if(data == "htm"){
                            return '<input type="checkbox" value="'+ row.id +'" /><span class="html-icon"></span><a href="javascript:void(0)" ng-click="getcontent('+row.id+')">'+row.filename+'.htm</a>';
                        }
                    },"fnCreatedCell": function (nTd, sData, oData, iRow, iCol) {
                    $compile(nTd)($scope);
                },
                    "targets": 0
                },
                {
                    "render":function(data, type, row){
                        if(data==0&&row.suffix==""){
                            return '';
                        }else{
                            return getTime.bytesToSize(data);
                        }
                    },
                    "targets":1
                },
                {
                    "render":function(data, type, row){
                        return getTime.getLocalTime(data);
                    },
                    "targets":2
                },
                {
                    "render": function (data, type, row) {
                        if (data == "") {
                            return ' <button type="button" class="btn btn-danger" ng-click="delete('+row.id+')" zg-access="pagemanager/deleteHtml">删除</button>';
                            //return '<input type="checkbox" value="'+ row.id +'" /><span class="file-icon"></span><a href="/recycle/filedetail.html?id='+row.id+'">'+row.filename+'</a>';
                        } else if(data == "doc"||data == "docx"){
                            return ' <button type="button" class="btn btn-danger" ng-click="delete('+row.id+')" zg-access="pagemanager/deleteHtml">删除</button>';
                        } else if(data == "pdf"){
                            return ' <button type="button" class="btn btn-danger" ng-click="delete('+row.id+')" zg-access="pagemanager/deleteHtml">删除</button>';
                        }else if(data ==  "html"){
                            return '<button type="button" class="btn btn-danger" ng-click="delete('+row.id+')" zg-access="pagemanager/deleteHtml">删除</button><button type="button" class="btn btn-success" ng-click="instantiateTextbox('+row.id+')" zg-access="pagemanager/getHtmlContent">编辑</button><button type="button" class="btn btn-info" ng-click="getcontent('+row.id+')" zg-access="pagemanager/previewHtml">浏览</button>';
                        }else if(data ==  "htm"){
                            return '<button type="button" class="btn btn-danger" ng-click="delete('+row.id+')" zg-access="pagemanager/deleteHtml">删除</button><button type="button" class="btn btn-success" ng-click="instantiateTextbox('+row.id+')" zg-access="pagemanager/getHtmlContent">编辑</button><button type="button" class="btn btn-info" ng-click="getcontent('+row.id+')" zg-access="pagemanager/previewHtml">浏览</button>';
                        }
                    },"fnCreatedCell": function (nTd, sData, oData, iRow, iCol) {
                    $compile(nTd)($scope);
                },
                    "targets": 3
                },
            ],
        });
    };
    $(document).ready(function(){
        $scope.loadTable();
        if(angular.isUndefined($scope.fatherid)){
            $scope.fatherid="";
        }
        $("#bread-crumbs").empty();
        var html='<li><a href="javascript:void(0)">全部文件</a></li>';
        $("#bread-crumbs").append(html);
        getStorage.newStorage();
    });
    //批量删除
    $scope.deleteBatch=function(){
        var ipts = $(":checkbox:checked");
        var arr=[];
        ipts.each(function(){
            arr.push($(this).val());
        });
        if(arr.length<1){
            toastr.warning("请选择一个数据")
        }else{
            $("#deleteSure").modal("show");
            $scope.sureDelete=function(){
                $http( {
                    method: 'post',
                    url:Url+'pagemanager/deleteHtml',
                    withCredentials:true,
                    headers:{
                        Authorization:token
                    },
                    data:{id:arr}
                }).then(function successCallback(response) {
                    if(response.data.code==0){
                        toastr.success("删除成功");
                        if($scope.fatherid){
                            $scope.fileDetail($scope.fatherid);
                        }else{
                            $scope.loadTable();
                        }
                        getStorage.newStorage();
                        $("#deleteSure").modal("hide");
                    }else{
                        toastr.error(response.data.message);
                    }
                },function errorCallback(response){
                    // console.log(response.data)
                });
            }
        }
    };
    //删除单个文件
    $scope.delete=function(id){
        $("#deleteSure").modal("show");
        $scope.sureDelete=function(){
            $http( {
                method: 'post',
                url:Url+'pagemanager/deleteHtml',
                withCredentials:true,
                headers:{
                    Authorization:token
                },
                data:{id:id}
            }).then(function successCallback(response) {
                if(response.data.code==0){
                    toastr.success("删除成功");
                    if($scope.fatherid){
                        $scope.fileDetail($scope.fatherid);
                    }else{
                        $scope.loadTable();
                    }
                    getStorage.newStorage();
                    $("#deleteSure").modal("hide");
                }else{
                    toastr.error(response.data.message);
                }
            },function errorCallback(response){
                // console.log(response.data)
            });
        }
    };
    //文件上传
    Dropzone.options.myAwesomeDropzone = false;
    Dropzone.autoDiscover = false;
    $scope.openUpload=function(){
        $("#uploadHtml").modal("show");
        $scope.filepath ="";
        var myDropzone = new Dropzone("#dropzoneHtml", {
            url:Url+'pagemanager/uploadHTMLFile?tenanid='+user.tenanid+'&userid='+user.userid+'',
            withCredentials:true,
            headers:{
                Authorization:token
            },
            method:"post",  //也可用put
            paramName:"uploadfile", //默认为file
            maxThumbnailFilesize: 10,
            maxFiles:10,
            parallelUploads: 100,
            maxFilesize:20,//单位为MB
            autoProcessQueue: false,
            uploadMultiple:true,
            hiddenInputContainer:true,
            acceptedFiles: ".html,.htm", //上传的类型
            addRemoveLinks:true,
            // previewsContainer:"#preview",//上传图片的预览窗口
            dictDefaultMessage:'拖动文件至此或者点击上传',
            dictMaxFilesExceeded: "您最多只能上传1个文件！",
            dictResponseError: '文件上传失败!',
            dictInvalidFileType: "文件类型只能是*.html。",
            dictFallbackMessage:"浏览器不受支持",
            dictFileTooBig:"文件过大上传文件最大支持.",
            dictRemoveFile: "删除",
            dictCancelUpload: "取消",
            init:function(){
                this.on("addedfile", function(file) {
                    //上传文件时触发的事件
                    document.querySelector('div .dz-default').style.display = 'none';
                    $scope.file = file;
                    $scope.filepath = file.fullPath + "|" + $scope.filepath;
                    $scope.$apply(function() {
                        $scope.fileAdded = true;
                    });
                });
                this.on("sending",function (file, xhr, formData) {
                    formData.append("filepath", $scope.filepath);
                    formData.append("fatherid", $scope.fatherid);
                });
                this.on("success",function(file,response){
                    //上传成功触发的事件
                    $scope.filepath ="";
                    if(response.code==0){
                        toastr.success("上传成功");
                        $("#uploadHtml").modal("hide");
                        if($scope.fatherid){
                            $scope.fileDetail($scope.fatherid);
                        }else{
                            $scope.loadTable();
                        }
                        myDropzone.removeAllFiles();
                        getStorage.newStorage();
                    }else{
                        toastr.error(response.message);
                    }
                });
                this.on("error",function (file,response) {
                    //上传失败触发的事件
                    if(response.code!==0){
                        toastr.error(response);
                    }
                });
                this.on("maxfilesreached",function(){
                    toastr.error("文件数量超过最大件数！");
                    myDropzone.removeAllFiles(file);
                });
                this.on("removedfile",function(file){
                    var para;
                    if("undefined" == new String(file.fullPath)) {
                        //para = file.name;
                        para = file.fullPath;
                    } else {
                        para = file.fullPath;
                    }
                    $scope.filepath= $scope.filepath.replace(para+"|","");
                    document.querySelector('div .dz-default').style.display = 'block';
                });
            }
        });
        $scope.uploadFile = function(fatherid) {
            myDropzone.processQueue();
        };

        $scope.reset = function() {
            myDropzone.removeAllFiles();
        };
    };
    //获取文件夹详情
    $scope.fileDetail=function(id){
        $.fn.dataTable.ext.errMode = 'none';
        $('#page_managementTable').empty();
        $('#page_managementTable').dataTable({
            "bDestroy" : true,//不加这个在第二次展示此表格时报错
            "destroy": true,
            "searching": true,
            "bAutoWidth": true, //是否自适应宽度
            "sPaginationType": "full_numbers",
            "serverSide": true,//开启服务器模式，使用服务器端处理配置datatable
            "bPaginage": true,
            "bDeferRender":true,
            "ordering": false, // 禁止排序
            "bFilter" : true, //是否启动过滤、搜索功能
            "language": {
                "sProcessing": "加载中...",
                "sLengthMenu": "显示 _MENU_ 项结果",
                "sZeroRecords": "没有匹配结果",
                "sInfo": "显示第 _START_ 至 _END_ 项结果，共 _TOTAL_ 项",
                "sInfoEmpty": "显示第 0 至 0 项结果，共 0 项",
                "sInfoFiltered": "(由 _MAX_ 项结果过滤)",
                "sInfoPostFix": "",
                "sSearch": "过滤:",
                "sEmptyTable": "表中数据为空",
                "sLoadingRecords": "载入中...",
                "sInfoThousands": ",",
                "oPaginate": {
                    "sFirst": "首页",
                    "sPrevious": "上页",
                    "sNext": "下页",
                    "sLast": "末页"
                },
                "oAria": {
                    "sSortAscending": ": 以升序排列此列",
                    "sSortDescending": ": 以降序排列此列"
                }
            },
            "fnPreDrawCallback": function( oSettings ) {
                $('.dataTables_filter input').attr({'name':'search','placeholder': '请输入用户名称'});//提示
            },
            "ajax":{
                "url":Url+'pagemanager/getHtmlFolder?id='+id+'&flag='+flag+'',
                "headers":{
                    "Authorization":token
                },
                "xhrFields": {
                    "withCredentials": true
                },
                error: function(){
                    $state.go("403");
                }
            },

            "columns": [
                {"data": "suffix"},
                {"data": "size"},
                {"data": "updatetime"},
                {"data": "suffix"}
            ],
            "columnDefs": [
                {
                    "render": function (data, type, row) {
                        if (data == "") {
                            return '<input type="checkbox" value="'+ row.id +'" /><span class="file-icon"></span><a href="javascript:void(0)" ng-click="fileDetail('+row.id+')">'+row.filename+'</a>';
                            //return '<input type="checkbox" value="'+ row.id +'" /><span class="file-icon"></span><a href="/recycle/filedetail.html?id='+row.id+'">'+row.filename+'</a>';
                        } else if(data == "doc"){
                            return '<input type="checkbox" value="'+ row.id +'" /><span class="doc-icon"></span><a href="#">'+row.filename+'.doc</a>';
                        } else if(data == "docx"){
                            return '<input type="checkbox" value="'+ row.id +'" /><span class="doc-icon"></span><a href="#">'+row.filename+'.docx</a>';
                        } else if(data == "pdf"){
                            return '<input type="checkbox" value="'+ row.id +'" /><span class="pdf-icon"></span><a href="#">'+row.filename+'.pdf</a>';
                        }else if(data ==  "html"){
                            return '<input type="checkbox" value="'+ row.id +'" /><span class="html-icon"></span><a href="#" ng-click="getcontent('+row.id+')">'+row.filename+'.html</a>';
                        }else if(data == "htm"){
                            return '<input type="checkbox" value="'+ row.id +'" /><span class="html-icon"></span><a href="#" ng-click="getcontent('+row.id+')">'+row.filename+'.htm</a>';
                        }
                    },"fnCreatedCell": function (nTd, sData, oData, iRow, iCol) {
                    $compile(nTd)($scope);
                },
                    "targets": 0
                },
                {
                    "render":function(data, type, row){
                        if(data==0&&row.suffix==""){
                            return '';
                        }else{
                            return getTime.bytesToSize(data);
                        }
                    },
                    "targets":1
                },
                {
                    "render":function(data, type, row){
                        return getTime.getLocalTime(data);
                    },
                    "targets":2
                },
                {
                    "render": function (data, type, row) {
                        if (data == "") {
                            return ' <button type="button" class="btn btn-danger" ng-click="delete('+row.id+')" zg-access="pagemanager/deleteHtml">删除</button>';
                        } else if(data == "doc"||data == "docx"){
                            return ' <button type="button" class="btn btn-danger" ng-click="delete('+row.id+')" zg-access="pagemanager/deleteHtml">删除</button>';
                        } else if(data == "pdf"){
                            return ' <button type="button" class="btn btn-danger" ng-click="delete('+row.id+')" zg-access="pagemanager/deleteHtml">删除</button> ';
                        }else if(data ==  "html"){
                            return '<button type="button" class="btn btn-danger" ng-click="delete('+row.id+')" zg-access="pagemanager/deleteHtml">删除</button><button type="button" class="btn btn-success" ng-click="instantiateTextbox('+row.id+')" zg-access="pagemanager/getHtmlContent">编辑</button><button type="button" class="btn btn-info" ng-click="getcontent('+row.id+')" zg-access="pagemanager/previewHtml">浏览</button>';
                        }else if(data ==  "htm"){
                            return '<button type="button" class="btn btn-danger" ng-click="delete('+row.id+')" zg-access="pagemanager/deleteHtml">删除</button><button type="button" class="btn btn-success" ng-click="instantiateTextbox('+row.id+')" zg-access="pagemanager/getHtmlContent">编辑</button><button type="button" class="btn btn-info" ng-click="getcontent('+row.id+')" zg-access="pagemanager/previewHtml">浏览</button>';
                        }
                    },"fnCreatedCell": function (nTd, sData, oData, iRow, iCol) {
                    $compile(nTd)($scope);
                },
                    "targets": 3
                }
            ]
        });
        //面包屑展示
        $http({
            method: 'post',
            url:Url+'pagemanager/getHtmlFolder?id='+id+'',
            withCredentials:true,
            headers:{
                Authorization:token
            },
            data:{id:id}
        }).then(function successCallback(response) {
            if(response.data.code==0){
                $scope.fatherid=id;
                //面包屑
                $("#bread-crumbs").empty();
                var compileFn = $compile('<li><a href="javascript:void(0);" ng-click="backoff('+id+')" class="front">返回上一页</a><span>|</span></li><li><span>全部文件</span><span>'+response.data.localpath+'</span></li>');
                var $dom = compileFn($scope);
                $("#bread-crumbs").append($dom);
            }else{
                toastr.error(response.data.message);
            }
        },function errorCallback(response){
            // console.log(response.data)
        });
    };
    //编辑文件
    $scope.instantiateTextbox = function (id) {
        $("#editorBox").modal("show");
        textboxio.replaceAll('textarea', {
            paste: {
                style: 'clean'
            },
            css: {
                stylesheets: ['lib/textboxio-client/example.css']
            },
            codeview: { enabled: false,showButton: false },
        });
        $http({
            method: 'post',
            url:Url+'filemanager/editHtml?tenanid='+user.tenanid+'&userid='+user.userid+'&id='+id+'',
            withCredentials:true,
            headers:{
                Authorization:token
            },
            data:{id:id}
        }).then(function successCallback(response) {
            if(response.data.code==0){
                var divEditor = textboxio.replace('#content');
                var content = divEditor.content.set(response.data.data[0].data);
                //var content = divEditor.con tent.set(response.data.data.data);
            }
        },function errorCallback(response){
            toastr.error(response.data.message);
        });
        $scope.changeEditorContent = function(){
            var editors = textboxio.get('#content');
            var editor = editors[0];
            var content=editor.content.get();
            $http({
                method: 'post',
                url:Url+'pagemanager/uploadHTML?tenanid='+user.tenanid+'&userid='+user.userid+'&id='+id+'',
                withCredentials:true,
                headers:{
                    Authorization:token
                },
                data:{htmlfile:content,flag:flag}
            }).then(function successCallback(response) {
                if(response.data.code==0){
                    toastr.success('文件编辑成功！');
                    if($scope.fatherid){
                        $scope.fileDetail($scope.fatherid)
                    }else{
                        $scope.loadTable()
                    }
                    var content = editor.content.set("");
                    $("#editorBox").modal("hide");
                    getStorage.newStorage();
                }else{
                    toastr.error(response.data.message);
                }
            },function errorCallback(response){
                toastr.error(response.data.message);
            });
        };
    };
    //新建html
    $scope.newHtml=function(){
        $("#addSure").modal('show');
        $scope.sureName=function(){
            var name=$scope.htmlname;
            if(angular.isUndefined(name)){
                name="";
                toastr.warning("文件名称不能为空");
            }else{
                $("#addSure").modal('hide');
                $("#textbox1").modal("show");
                textboxio.replaceAll('textarea', {
                    paste: {
                        style: 'clean'
                    },
                    css: {
                        stylesheets: ['lib/textboxio-client/example.css']
                    },
                    codeview: { enabled: false,showButton: false },
                });
                $scope.sureAdd = function(){
                    var editors = textboxio.get('#textbox');
                    var editor = editors[0];
                    var content=editor.content.get();
                    $http({
                        method: 'post',
                        url:Url+'pagemanager/uploadHTML?tenanid='+user.tenanid+'&userid='+user.userid+'&fatherid='+$scope.fatherid+'',
                        withCredentials:true,
                        headers:{
                            Authorization:token
                        },
                        data:{htmlfile:content,htmlname:name}
                    }).then(function successCallback(response) {
                        if(response.data.code==0){
                            toastr.success(response.data.message);
                           if($scope.fatherid){
                               $scope.fileDetail($scope.fatherid);
                           }else{
                               $scope.loadTable();
                           }
                            getStorage.newStorage();
                            $scope.htmlname="";
                            var content = editor.content.set("");
                            $("#textbox1").modal("hide");
                        }else{
                            toastr.error(response.data.message);
                        }
                    },function errorCallback(response){
                        toastr.error(response.data.message);
                    });
                };
            }
        }
    };
    //新建文件夹
    $scope.newFolder=function(){
        var compileFn = $compile('<tr class="odd gradeX"><td><input type="checkbox" value="1"><span class="file-icon"></span> <input type="text" class="form-control" placeholder="新建文件夹" style="width:50%;display:inline-block" id="newfolder" ng-model="filename" minlength="1" maxlength="50"> <span class="glyphicon glyphicon-ok" ng-click="saveFolder()"></span> <span class="glyphicon glyphicon-remove" ng-click="closeFolder()"></span></td><td></td><td></td><td></td></tr>');
        var $dom = compileFn($scope);
        $("table tr:eq(0)").after($dom);
        //确定新建文件夹
        $scope.saveFolder=function(){
            var name=$scope.filename;
            $http({
                method: 'post',
                url:Url+'pagemanager/saveFolder',
                withCredentials:true,
                headers:{
                    Authorization:token
                },
                data:{filename:name,userid:user.userid,tenanid:user.tenanid,fatherid:$scope.fatherid}
            }).then(function successCallback(response) {
                if(response.data.code==0){
                    toastr.success(response.data.message);
                    if($scope.fatherid){
                        $scope.fileDetail($scope.fatherid);
                    }else{
                        $scope.loadTable();
                    }
                    $scope.filename="";
                    $scope.closeFolder();
                }else{
                    toastr.error(response.data.message);
                }
            },function errorCallback(response){
                toastr.error(response.data.message);
            });
        }
    };
    //取消新建文件夹
    $scope.closeFolder=function(){
        $('table tr:eq(1)').remove();
        $("#newfolder").val("");
    }
    //返回上一级目录
    $scope.backoff=function(id){
        $http({
            method: 'post',
            url:Url+'pagemanager/backoff',
            withCredentials:true,
            headers:{
                Authorization:token
            },
            data:{id:id,flag:flag}
        }).then(function successCallback(response) {
            if(response.data.code==0){
                $.fn.dataTable.ext.errMode = 'none';
                $("#page_managementTable").empty();
                $('#page_managementTable').dataTable({
                    "destroy": true,
                    "searching": true,
                    "bAutoWidth": true, //是否自适应宽度
                    "sPaginationType": "full_numbers",
                    "serverSide": true,//开启服务器模式，使用服务器端处理配置datatable
                    "bPaginage": true,
                    "bDeferRender":true,
                    "ordering": false, // 禁止排序
                    "bFilter" : true, //是否启动过滤、搜索功能
                    "language": {
                        "sProcessing": "加载中...",
                        "sLengthMenu": "显示 _MENU_ 项结果",
                        "sZeroRecords": "没有匹配结果",
                        "sInfo": "显示第 _START_ 至 _END_ 项结果，共 _TOTAL_ 项",
                        "sInfoEmpty": "显示第 0 至 0 项结果，共 0 项",
                        "sInfoFiltered": "(由 _MAX_ 项结果过滤)",
                        "sInfoPostFix": "",
                        "sSearch": "过滤:",
                        "sEmptyTable": "表中数据为空",
                        "sLoadingRecords": "载入中...",
                        "sInfoThousands": ",",
                        "oPaginate": {
                            "sFirst": "首页",
                            "sPrevious": "上页",
                            "sNext": "下页",
                            "sLast": "末页"
                        },
                        "oAria": {
                            "sSortAscending": ": 以升序排列此列",
                            "sSortDescending": ": 以降序排列此列"
                        }
                    },
                    "fnPreDrawCallback": function( oSettings ) {
                        $('.dataTables_filter input').attr({'name':'search','placeholder': '请输入文件名称'});//提示
                    },
                    "ajax":{
                        "url":Url+'pagemanager/backoff?id='+id+'&flag='+flag+'',
                        "headers":{
                            "Authorization":token
                        },
                        "xhrFields": {
                            "withCredentials": true
                        },
                        error: function(){
                            $state.go("403");
                        }
                    },
                    "columns": [
                        {"data": "suffix"},
                        {"data": "size"},
                        {"data": "updatetime"},
                        {"data": "suffix"}
                    ],
                    "columnDefs": [
                        {
                            "render": function (data, type, row) {
                                if (data == "") {
                                    return '<input type="checkbox" value="'+ row.id +'" /><span class="file-icon"></span><a href="javascript:void(0)" ng-click="fileDetail('+row.id+')" zg-access="pagemanager/getHtmlFolder">'+row.filename+'</a>';
                                } else if(data == "doc"){
                                    return '<input type="checkbox" value="'+ row.id +'" /><span class="doc-icon"></span><a href="#">'+row.filename+'.doc</a>';
                                } else if(data == "docx"){
                                    return '<input type="checkbox" value="'+ row.id +'" /><span class="doc-icon"></span><a href="#">'+row.filename+'.docx</a>';
                                } else if(data == "pdf"){
                                    return '<input type="checkbox" value="'+ row.id +'" /><span class="pdf-icon"></span><a href="#">'+row.filename+'.pdf</a>';
                                } else if(data == "html"){
                                    return '<input type="checkbox" value="'+ row.id +'" /><span class="html-icon"></span><a href="#" ng-click="getcontent('+row.id+')">'+row.filename+'.html</a>';
                                }else if(data == "htm"){
                                    return '<input type="checkbox" value="'+ row.id +'" /><span class="html-icon"></span><a href="#" ng-click="getcontent('+row.id+')">'+row.filename+'.htm</a>';
                                }
                            },"fnCreatedCell": function (nTd, sData, oData, iRow, iCol) {
                            $compile(nTd)($scope);
                        },
                            "targets": 0
                        },
                        {
                            "render":function(data, type, row){
                                if(data==0&&row.suffix==""){
                                    return '';
                                }else{
                                    return getTime.bytesToSize(data);
                                }
                            },
                            "targets":1
                        },
                        {
                            "render":function(data, type, row){
                                return getTime.getLocalTime(data);
                            },
                            "targets":2
                        },
                        {
                            "render": function (data, type, row) {
                                if (data == "") {
                                    return ' <button type="button" class="btn btn-danger" ng-click="delete('+row.id+')" zg-access="pagemanager/deleteHtml">删除</button>';
                                    //return '<input type="checkbox" value="'+ row.id +'" /><span class="file-icon"></span><a href="/recycle/filedetail.html?id='+row.id+'">'+row.filename+'</a>';
                                } else if(data == "doc"||data == "docx"){
                                    return ' <button type="button" class="btn btn-danger" ng-click="delete('+row.id+')" zg-access="pagemanager/deleteHtml">删除</button> <button type="button" class="btn btn-success" zg-access="filemanager/convertFile">转换</button>';
                                } else if(data == "pdf"){
                                    return ' <button type="button" class="btn btn-danger" ng-click="delete('+row.id+')" zg-access="pagemanager/deleteHtml">删除</button> <button type="button" class="btn btn-success" zg-access="filemanager/convertFile">转换</button>';
                                }else if(data ==  "html"){
                                    return '<button type="button" class="btn btn-danger" ng-click="delete('+row.id+')" zg-access="pagemanager/deleteHtml">删除</button><button type="button" class="btn btn-success" ng-click="instantiateTextbox('+row.id+')" zg-access="pagemanager/getHtmlContent">编辑</button><button type="button" class="btn btn-info" ng-click="getcontent('+row.id+')" zg-access="pagemanager/previewHtml">浏览</button>';
                                }else if(data ==  "htm"){
                                    return '<button type="button" class="btn btn-danger" ng-click="delete('+row.id+')" zg-access="pagemanager/deleteHtml">删除</button><button type="button" class="btn btn-success" ng-click="instantiateTextbox('+row.id+')" zg-access="pagemanager/getHtmlContent">编辑</button><button type="button" class="btn btn-info" ng-click="getcontent('+row.id+')" zg-access="pagemanager/previewHtml">浏览</button>';
                                }
                            },"fnCreatedCell": function (nTd, sData, oData, iRow, iCol) {
                            $compile(nTd)($scope);
                        },
                            "targets": 3
                        }
                    ]
                });
                if(response.data.id){
                    $scope.fatherid=response.data.id;
                    $("#bread-crumbs").empty();
                    var compileFn = $compile('<li><a href="javascript:void(0);" ng-click="backoff('+response.data.id+')" class="front">返回上一页</a><span>|</span></li><li><span>全部文件</span><span>'+response.data.localPath+'</span></li>');
                    var $dom = compileFn($scope);
                    $("#bread-crumbs").append($dom);
                }else{
                    $scope.fatherid="";
                    $("#bread-crumbs").empty();
                    var html='<li><a href="javascript:void(0)">全部文件</a></li>';
                    $("#bread-crumbs").append(html);
                }
            }else{
                toastr.error(response.data.message);
            }
        },function errorCallback(response){
            toastr.error(response.data.message);
        });
    }
    //浏览网页
    $scope.getcontent=function(id){
        $http({
            method: 'post',
            url:Url+'filemanager/glanceHtml',
            withCredentials:true,
            headers:{
                Authorization:token
            },
            data:{id:id}
        }).then(function successCallback(response) {
            if(response.data.code==0){
                var data=response.data.data.data;
                var url=preUrl+data;
                $window.open(url);
            }else{
                toastr.error(response.data.message);
            }
        },function errorCallback(response){
            toastr.error(response.data.message);
        });
    }
});
//视频的控制器
app.controller('videoCtrl',function ($scope,$http,$compile,getTime,$state,$sessionStorage,$window,getStorage) {
    var user = angular.fromJson($sessionStorage.USER);
    $scope.user=user;
    var flag=$sessionStorage.CJGLYFLG;
    //表格展示
    $scope.loadTable=function(){
        $.fn.dataTable.ext.errMode = 'none';
        $('#videoTable').dataTable({
            "destroy": true,
            "searching": true,
            "bAutoWidth": true, //是否自适应宽度
            "sPaginationType": "full_numbers",
            "serverSide": true,//开启服务器模式，使用服务器端处理配置datatable
            //"processing": true,//开启读取服务器数据时显示正在加载中……特别是大数据量的时候，开启此功能比较好
            "bPaginage": true,
            "bDeferRender":true,
            "ordering": false, // 禁止排序
            "bFilter" : true, //是否启动过滤、搜索功能
            "language": {
                "sProcessing": "加载中...",
                "sLengthMenu": "显示 _MENU_ 项结果",
                "sZeroRecords": "没有匹配结果",
                "sInfo": "显示第 _START_ 至 _END_ 项结果，共 _TOTAL_ 项",
                "sInfoEmpty": "显示第 0 至 0 项结果，共 0 项",
                "sInfoFiltered": "(由 _MAX_ 项结果过滤)",
                "sInfoPostFix": "",
                "sSearch": "过滤:",
                "sEmptyTable": "表中数据为空",
                "sLoadingRecords": "载入中...",
                "sInfoThousands": ",",
                "oPaginate": {
                    "sFirst": "首页",
                    "sPrevious": "上页",
                    "sNext": "下页",
                    "sLast": "末页"
                },
                "oAria": {
                    "sSortAscending": ": 以升序排列此列",
                    "sSortDescending": ": 以降序排列此列"
                }
            },
            "fnPreDrawCallback": function( oSettings ) {
                $('.dataTables_filter input').attr({'name':'search','placeholder': '请输入视频名称'});//提示
            },
            "ajax":{
                "url":Url+'filemanager/selectVideoListByParameter?tenanid='+user.tenanid+'&userid='+user.userid+'&flag='+flag+'',
                "headers":{
                    "Authorization":token
                },
                "xhrFields": {
                    "withCredentials": true
                },
                error: function(){
                    $state.go("403");
                }
            },

            "columns": [
                {"data": "suffix"},
                {"data": "size"},
                {"data": "updatetime"},
                {"data": "suffix"},
            ],
            "columnDefs": [
                {
                    "render": function (data, type, row) {
                        return '<input type="checkbox" value="'+ row.id +'" /><span class="doc-icon"></span><a href="#">'+row.filename+'.mp4</a>';
                    },"fnCreatedCell": function (nTd, sData, oData, iRow, iCol) {
                    $compile(nTd)($scope);
                },
                    "targets": 0
                },
                {
                    "render":function(data, type, row){
                        if(data==0&&row.suffix==""){
                            return '';
                        }else{
                            return getTime.bytesToSize(data);
                        }
                    },
                    "targets":1
                },
                {
                    "render":function(data, type, row){
                        return getTime.getLocalTime(data);
                    },
                    "targets":2
                },
                {
                    "render": function (data, type, row) {
                        return '<button type="button" class="btn btn-danger" ng-click="delete('+row.id+')" zg-access="filemanager/delete">删除</button>';
                    },"fnCreatedCell": function (nTd, sData, oData, iRow, iCol) {
                    $compile(nTd)($scope);
                },
                    "targets": 3
                },
            ],
        });
    };
    $(document).ready(function(){
        $scope.loadTable();
        getStorage.newStorage();
    });
    //视频上传
    Dropzone.options.myAwesomeDropzone = false;
    Dropzone.autoDiscover = false;
    $scope.openUpload=function(){
        $("#uploadVideo").modal("show");
        $scope.filepath ="";
        var myDropzone = new Dropzone("#dropzoneVideo", {
            url:Url+'filemanager/uploadVideo?tenanid='+user.tenanid+'&userid='+user.userid+'',
            withCredentials:true,
            headers:{
                Authorization:token
            },
            method:"post",  //也可用put
            paramName:"uploadfile", //默认为file
            maxThumbnailFilesize: 20,
            maxFiles:10,
            parallelUploads: 100,
            maxFilesize: 20,//单位为MB
            autoProcessQueue: false,
            uploadMultiple:true,
            hiddenInputContainer:true,
            acceptedFiles: ".mp4,.avi", //上传的类型
            addRemoveLinks:true,
            // previewsContainer:"#preview",//上传图片的预览窗口
            dictDefaultMessage:'拖动文件至此或者点击上传',
            dictMaxFilesExceeded: "您最多只能上传1个文件！",
            dictResponseError: '文件上传失败!',
            dictInvalidFileType: "文件类型只能是*mp4,*.avi。",
            dictFallbackMessage:"浏览器不受支持",
            dictFileTooBig:"文件超过最大上传文件的限制.",
            dictRemoveFile: "删除",
            dictCancelUpload: "取消",
            init:function(){
                this.on("addedfile", function(file) {
                    //上传文件时触发的事件
                    document.querySelector('div .dz-default').style.display = 'none';
                    $scope.file = file;
                    $scope.filepath = file.fullPath + "|" + $scope.filepath;
                    $scope.$apply(function() {
                        $scope.fileAdded = true;
                    });
                });
                this.on("sending",function (file, xhr, formData) {
                    formData.append("filepath", $scope.filepath);
                })
                this.on("success",function(file,response){
                    //上传成功触发的事件
                    $scope.filepath ="";
                    if(response.code==0){
                        toastr.success("上传成功");
                        $("#uploadVideo").modal("hide");
                        $scope.loadTable();
                        getStorage.newStorage();
                        $scope.reset();
                    }else{
                        toastr.error(response.message);
                    }
                });
                this.on("error",function (file,response) {
                    //上传失败触发的事件
                    if(response.code!==0){
                        toastr.error(response);
                        $scope.reset();
                    }
                });
                this.on("maxfilesreached",function(){
                    toastr.warning("文件数量已达到最大限制！");
                });
                this.on("removedfile",function(file){
                    var para;
                    if("undefined" == new String(file.fullPath)) {
                        //para = file.name;
                        para = file.fullPath;
                    } else {
                        para = file.fullPath;
                    }
                    $scope.filepath= $scope.filepath.replace(para+"|","");
                    document.querySelector('div .dz-default').style.display = 'block';
                });
            }
        });
        $scope.uploadFile = function() {
            myDropzone.processQueue();
        };

        $scope.reset = function() {
            myDropzone.removeAllFiles();
            $("#uploadHtml").modal('hide');
        };
    };
    //批量删除
    $scope.deleteBatch=function() {
        var ipts = $(":checkbox:checked");
        var arr = [];
        ipts.each(function () {
            arr.push($(this).val());
        });
        if (arr.length < 1) {
            toastr.warning("请选择一个数据")
        } else {
            $("#deleteSure").modal("show");
            $scope.sureDelete = function () {
                $http({
                    method: 'post',
                    url: Url + 'filemanager/batchDelete',
                    withCredentials:true,
                    headers:{
                        Authorization:token
                    },
                    data: {ids: arr}
                }).then(function successCallback(response) {
                    if (response.data.flg == 0) {
                        toastr.success(response.data.message);
                        $scope.loadTable();
                        getStorage.newStorage();
                        $("#deleteSure").modal("hide");
                    } else {
                        toastr.error(response.data.message);
                    }
                }, function errorCallback(response) {
                    // console.log(response.data)
                });
            }
        }
    }
    //删除单个文件
    $scope.delete=function(id){
        $("#deleteSure").modal("show");
        $scope.sureDelete=function(){
            $http( {
                method: 'post',
                url:Url+'filemanager/delete',
                withCredentials:true,
                headers:{
                    Authorization:token
                },
                data:{id:id}
            }).then(function successCallback(response) {
                if(response.data.code==0){
                    toastr.success(response.data.message);
                    $scope.loadTable();
                    getStorage.newStorage();
                    $("#deleteSure").modal("hide");
                }else{
                    toastr.error(response.data.message);
                }
            },function errorCallback(response){
                // console.log(response.data)
            });
        }
    };
});
//回收站的控制器
app.controller('recycleCtrl',function ($http, $scope,$compile,getTime,$state,$sessionStorage,getStorage) {
    var user = angular.fromJson($sessionStorage.USER);
    $scope.user=user;
    var flag=$sessionStorage.CJGLYFLG;
    //表格展示
    $scope.loadTable=function(){
        $.fn.dataTable.ext.errMode = 'none';
        $('#recycleTable').dataTable({
            "destroy": true,
            "searching": true,
            "bAutoWidth": true, //是否自适应宽度
            "sPaginationType": "full_numbers",
            "serverSide": true,//开启服务器模式，使用服务器端处理配置datatable
            //"processing": true,//开启读取服务器数据时显示正在加载中……特别是大数据量的时候，开启此功能比较好
            "bPaginage": true,
            "bDeferRender":true,
            "ordering": false, // 禁止排序
            "bFilter" : true, //是否启动过滤、搜索功能
            "language": {
                "sProcessing": "加载中...",
                "sLengthMenu": "显示 _MENU_ 项结果",
                "sZeroRecords": "没有匹配结果",
                "sInfo": "显示第 _START_ 至 _END_ 项结果，共 _TOTAL_ 项",
                "sInfoEmpty": "显示第 0 至 0 项结果，共 0 项",
                "sInfoFiltered": "(由 _MAX_ 项结果过滤)",
                "sInfoPostFix": "",
                "sSearch": "过滤:",
                "sEmptyTable": "表中数据为空",
                "sLoadingRecords": "载入中...",
                "sInfoThousands": ",",
                "oPaginate": {
                    "sFirst": "首页",
                    "sPrevious": "上页",
                    "sNext": "下页",
                    "sLast": "末页"
                },
                "oAria": {
                    "sSortAscending": ": 以升序排列此列",
                    "sSortDescending": ": 以降序排列此列"
                }
            },
            "fnPreDrawCallback": function( oSettings ) {
                $('.dataTables_filter input').attr({'name':'search','placeholder': '请输入文件名称'});//提示
            },
            "ajax":{
                "url":Url+'recycle/getDeleteFile?userid='+user.userid+'&flag='+flag+'',
                "headers":{
                    "Authorization":token
                },
                "xhrFields": {
                    "withCredentials": true
                },
                error: function(){
                    $state.go("403");
                }
            },
            "columns": [
                {"data": "suffix"},
                {"data":"localpath"},
                {"data": "size"},
                {"data": "updatetime"},
                {
                    "data": "id",
                    "render": function (data, type, full, meta) {
                        return '<button type="button" class="btn btn-primary" ng-click="recovery('+data+')" zg-access="recycle/recoveryFilePrompt">恢复文件</button>  <button type="button" class="btn btn-danger" ng-click="deleteFile('+data+')" zg-access="recycle/deleteFileThorough">彻底删除</button>';
                    },"fnCreatedCell": function (nTd, sData, oData, iRow, iCol) {
                    $compile(nTd)($scope);
                },
                },

            ],
            "columnDefs": [
                {
                    "render": function (data, type, row) {
                        if (data == "") {
                            return '<span class="file-icon"></span><a href="javascript:void(0)" ng-click="fileDetail('+row.id+')" zg-access="recycle/getDeleteFileFolder">'+row.filename+'</a>';
                        } else if(data == "doc"){
                            return '<span class="doc-icon"></span><a href="#">'+row.filename+'.doc</a>';
                        } else if(data == "docx"){
                            return '<span class="doc-icon"></span><a href="#">'+row.filename+'.docx</a>';
                        } else if(data == "pdf"){
                            return '<span class="pdf-icon"></span><a href="#">'+row.filename+'.pdf</a>';
                        }else if(data ==  "html"){
                            return '<span class="html-icon"></span><a href="#">'+row.filename+'.html</a>';
                        }else if(data ==  "txt"){
                            return '<span class="doc-icon"></span><a href="#">'+row.filename+'.txt</a>';
                        }else if(data ==  "mp4"){
                            return '<span class="doc-icon"></span><a href="#">'+row.filename+'.mp4</a>';
                        }else if(data ==  "htm"){
                            return '<span class="html-icon"></span><a href="#">'+row.filename+'.htm</a>';
                        }
                    },"fnCreatedCell": function (nTd, sData, oData, iRow, iCol) {
                    $compile(nTd)($scope);
                },
                    "targets": 0
                },
                {
                    "render":function(data, type, row){
                        return getTime.getLocalTime(data);
                    },
                    "targets":3
                },
                {
                    "render":function(data, type, row){
                        if(data==0&&row.suffix==""){
                            return '';
                        }else{
                            return getTime.bytesToSize(data);
                        }
                    },
                    "targets":2
                },
            ],
        });
    };
    $(document).ready(function(){
        $scope.loadTable();
        getStorage.newStorage();
    });
    ////获取文件夹详情
    //$scope.fileDetail=function(id){
    //    $.fn.dataTable.ext.errMode = 'none';
    //    $('#recycleTable').empty();
    //    $('#recycleTable').dataTable({
    //        "destroy": true,
    //        "searching": true,
    //        "bAutoWidth": true, //是否自适应宽度
    //        "sPaginationType": "full_numbers",
    //        "serverSide": true,//开启服务器模式，使用服务器端处理配置datatable
    //        //"processing": false,//开启读取服务器数据时显示正在加载中……特别是大数据量的时候，开启此功能比较好
    //        "bPaginage": true,
    //        "bDeferRender":true,
    //        "ordering": false, // 禁止排序
    //        "bFilter" : true, //是否启动过滤、搜索功能
    //        "language": {
    //            "sProcessing": "处理中...",
    //            "sLengthMenu": "显示 _MENU_ 项结果",
    //            "sZeroRecords": "没有匹配结果",
    //            "sInfo": "显示第 _START_ 至 _END_ 项结果，共 _TOTAL_ 项",
    //            "sInfoEmpty": "显示第 0 至 0 项结果，共 0 项",
    //            "sInfoFiltered": "(由 _MAX_ 项结果过滤)",
    //            "sInfoPostFix": "",
    //            "sSearch": "过滤:",
    //            "sEmptyTable": "表中数据为空",
    //            "sLoadingRecords": "载入中...",
    //            "sInfoThousands": ",",
    //            "oPaginate": {
    //                "sFirst": "首页",
    //                "sPrevious": "上页",
    //                "sNext": "下页",
    //                "sLast": "末页"
    //            },
    //            "oAria": {
    //                "sSortAscending": ": 以升序排列此列",
    //                "sSortDescending": ": 以降序排列此列"
    //            }
    //        },
    //        "fnPreDrawCallback": function( oSettings ) {
    //            $('.dataTables_filter input').attr({'name':'search','placeholder': '请输入文件名称'});//提示
    //        },
    //        "ajax":{
    //            "url":Url+'recycle/getDeleteFileFolder?userid='+user.userid+'&id='+id+'&flag='+flag+'',
    //            "headers":{
    //                "Authorization":token
    //            },
    //            "xhrFields": {
    //                "withCredentials": true
    //            },
    //            error: function(){
    //                $state.go("403");
    //            }
    //        },
    //        "columns": [
    //            {"data": "suffix"},
    //            {"data": "size"},
    //            {"data": "updatetime"},
    //            {
    //                "data": "id",
    //                "render": function (data, type, full, meta) {
    //                    return '<button type="button" class="btn btn-primary" ng-click="recovery('+data+')" zg-access="recycle/recoveryFilePrompt">恢复文件</button>  <button type="button" class="btn btn-danger" ng-click="deleteFile('+data+')" zg-access="recycle/deleteFileThorough">彻底删除</button>';
    //                },"fnCreatedCell": function (nTd, sData, oData, iRow, iCol) {
    //                $compile(nTd)($scope);
    //            }
    //            }
    //
    //        ],
    //        "columnDefs": [
    //            {
    //                "render": function (data, type, row) {
    //                    if (data == "") {
    //                        return '<span class="file-icon"></span><a href="javascript:void(0)" ng-click="fileDetail('+row.id+')" zg-access="recycle/getDeleteFileFolder">'+row.filename+'</a>';
    //                    } else if(data == "doc"){
    //                        return '<span class="doc-icon"></span><a href="#">'+row.filename+'.doc</a>';
    //                    } else if(data == "docx"){
    //                        return '<span class="doc-icon"></span><a href="#">'+row.filename+'.docx</a>';
    //                    } else if(data == "pdf"){
    //                        return '<span class="pdf-icon"></span><a href="#">'+row.filename+'.pdf</a>';
    //                    }else if(data ==  "html"){
    //                        return '<span class="html-icon"></span><a href="#">'+row.filename+'.html</a>';
    //                    }else if(data ==  "txt"){
    //                        return '<span class="doc-icon"></span><a href="#">'+row.filename+'.txt</a>';
    //                    }else if(data ==  "mp4"){
    //                        return '<span class="doc-icon"></span><a href="#">'+row.filename+'.mp4</a>';
    //                    }
    //                },"fnCreatedCell": function (nTd, sData, oData, iRow, iCol) {
    //                $compile(nTd)($scope);
    //            },
    //                "targets": 0
    //            },
    //            {
    //                "render":function(data, type, row){
    //                    return getTime.getLocalTime(data);
    //                },
    //                "targets":2
    //            },
    //            {
    //                "render":function(data, type, row){
    //                   if(data==0&&row.suffix==""){
                        //    return '';
    //                  }else{
//                          return getTime.bytesToSize(data);
//                      }
    //                },
    //                "targets":1
    //            },
    //        ],
    //    });
    //    //面包屑展示
    //    $http({
    //        method: 'post',
    //        url:Url+'recycle/getDeleteFileFolder?id='+id+'&flag='+flag+'',
    //        withCredentials:true,
    //        headers:{
    //            Authorization:token
    //        },
    //        data:{id:id}
    //    }).then(function successCallback(response) {
    //        if(response.data.code==0){
    //            $scope.fatherid=id;
    //            //面包屑
    //            $("#bread-crumbs").empty();
    //            var compileFn = $compile('<li><a href="javascript:void(0);" ng-click="backoff('+id+')" zg-access="recycle/backoff" class="front">返回上一页</a><span>|</span></li><li><span >全部文件</span><span>'+response.data.localpath+'</span></li>');
    //            var $dom = compileFn($scope);
    //            $("#bread-crumbs").append($dom);
    //        }else{
    //            toastr.error(response.data.message);
    //        }
    //    },function errorCallback(response){
    //        toastr.error(response.data)
    //    });
    //};

    //恢复文件
    $scope.recovery=function(id){
        //if(angular.isUndefined(fatherid)){
        //    fatherid="";
        //}
        $("#recoverySure").modal("show");
        $scope.sureRecovery=function(){
            $http( {
                method: 'post',
                url:Url+'recycle/recoveryFile',
                withCredentials:true,
                headers:{
                    Authorization:token
                },
                data:{id:id,state:0}
            }).then(function successCallback(response) {
                if(response.data.code==0){
                    toastr.success("文件恢复成功");
                    $scope.loadTable();
                    getStorage.newStorage();
                    $("#recoverySure").modal("hide");
                }else if(response.data.code==1){
                    //重名文件恢复
                    //var oldid=response.data.data;
                    $("#recoverySure").modal("hide");
                    $("#coverSure").modal("show");
                    $scope.sureCover=function(){
                        $http( {
                            method: 'post',
                            url:Url+'recycle/recoveryFile',
                            withCredentials:true,
                            headers:{
                                Authorization:token
                            },
                            data:{id:id,state:1}
                        }).then(function successCallback(response) {
                            if(response.data.code==0){
                                toastr.success(response.data.message);
                                $scope.loadTable();
                                $("#coverSure").modal("hide");
                            }else{
                                toastr.error(response.data.message);
                            }
                        },function errorCallback(response){
                            toastr.error(response.data.message);
                        });
                    };
                }else{
                    toastr.error(response.data.message);
                }
            },function errorCallback(response){
                toastr.error(response.data.message);
            });
        };
    };
    //彻底删除
    $scope.deleteFile=function(id){
        //if(angular.isUndefined(fatherid)){
        //    fatherid="";
        //}
        $("#deleteSure").modal("show");
        $scope.sureDelete=function(){
            $http({
                method: 'post',
                url:Url+'recycle/deleteFileThorough',
                withCredentials:true,
                headers:{
                    Authorization:token
                },
                data:{id:id}
            }).then(function successCallback(response) {
                if(response.data.code==0){
                    toastr.success("删除文件成功");
                    //if($scope.fatherid){
                    //    $scope.fileDetail($scope.fatherid);
                    //}else{
                    //    $scope.loadTable();
                    //}
                    $scope.loadTable();
                    getStorage.newStorage();
                    $("#deleteSure").modal("hide");
                }else{
                    toastr.error(response.data.message);
                }
            },function errorCallback(response){
                toastr.error(response.data.message);
            });
        };
    };
    //清空回收站
    $scope.deleteAll=function(){
        var CheckBox=$("#recycleTable input");
        for(i=0;i<CheckBox.length;i++){
            CheckBox[i].checked=true;
        };
        $("#deleteSure").modal("show");
        $scope.sureDelete=function(){
            $http( {
                method: 'post',
                url:Url+'recycle/emptyRecycle',
                withCredentials:true,
                headers:{
                    Authorization:token
                },
                data:{userid:user.userid,flag:flag}
            }).then(function successCallback(response) {
                $("#deleteSure").modal("hide");
                if(response.data.code==0){
                    toastr.success(response.data.message);
                    $scope.loadTable();
                    //$("#deleteSure").modal("hide");
                }else{
                    toastr.error(response.data.message);
                    //$("#deleteSure").modal("hide");
                }
            },function errorCallback(response){
                // console.log(response.data)
            });
        }
    };
    //返回上一级目录
    //$scope.backoff=function(id){
    //    $http({
    //        method: 'post',
    //        url:Url+'recycle/backoff',
    //        withCredentials:true,
    //        headers:{
    //            Authorization:token
    //        },
    //        data:{id:id,flag:flag}
    //    }).then(function successCallback(response) {
    //        if(response.data.code==0){
    //            $.fn.dataTable.ext.errMode = 'none';
    //            $("#recycleTable").empty();
    //            $('#recycleTable').dataTable({
    //                "destroy": true,
    //                "searching": true,
    //                "bAutoWidth": true, //是否自适应宽度
    //                "sPaginationType": "full_numbers",
    //                "serverSide": true,//开启服务器模式，使用服务器端处理配置datatable
    //                //"processing": true,//开启读取服务器数据时显示正在加载中……特别是大数据量的时候，开启此功能比较好
    //                "bPaginage": true,
    //                "bDeferRender":true,
    //                "ordering": false, // 禁止排序
    //                "bFilter" : true, //是否启动过滤、搜索功能
    //                "language": {
    //                    "sProcessing": "加载中...",
    //                    "sLengthMenu": "显示 _MENU_ 项结果",
    //                    "sZeroRecords": "没有匹配结果",
    //                    "sInfo": "显示第 _START_ 至 _END_ 项结果，共 _TOTAL_ 项",
    //                    "sInfoEmpty": "显示第 0 至 0 项结果，共 0 项",
    //                    "sInfoFiltered": "(由 _MAX_ 项结果过滤)",
    //                    "sInfoPostFix": "",
    //                    "sSearch": "过滤:",
    //                    "sEmptyTable": "表中数据为空",
    //                    "sLoadingRecords": "载入中...",
    //                    "sInfoThousands": ",",
    //                    "oPaginate": {
    //                        "sFirst": "首页",
    //                        "sPrevious": "上页",
    //                        "sNext": "下页",
    //                        "sLast": "末页"
    //                    },
    //                    "oAria": {
    //                        "sSortAscending": ": 以升序排列此列",
    //                        "sSortDescending": ": 以降序排列此列"
    //                    }
    //                },
    //                "fnPreDrawCallback": function( oSettings ) {
    //                    $('.dataTables_filter input').attr({'name':'search','placeholder': '请输入文件名称'});//提示
    //                },
    //                "ajax":{
    //                    "url":Url+'recycle/backoff?id='+id+'&flag='+flag+'',
    //                    "headers":{
    //                        "Authorization":token
    //                    },
    //                    "xhrFields": {
    //                        "withCredentials": true
    //                    },
    //                    error: function(){
    //                        $state.go("403");
    //                    }
    //                },
    //                "columns": [
    //                    {"data": "suffix"},
    //                    {"data": "size"},
    //                    {"data": "updatetime"},
    //                    {
    //                        "data": "id",
    //                        "render": function (data, type, full, meta) {
    //                            return '<button type="button" class="btn btn-primary" ng-click="recovery('+data+')" zg-access="recycle/recoveryFilePrompt">恢复文件</button>  <button type="button" class="btn btn-danger" ng-click="deleteFile('+data+')" zg-access="recycle/deleteFileThorough">彻底删除</button>';
    //                        },"fnCreatedCell": function (nTd, sData, oData, iRow, iCol) {
    //                        $compile(nTd)($scope);
    //                    }
    //                    }
    //                ],
    //                "columnDefs": [
    //                    {
    //                        "render": function (data, type, row) {
    //                            if (data == "") {
    //                                return '<input type="checkbox" value="'+ row.id +'" /><span class="file-icon"></span><a href="javascript:void(0)" ng-click="fileDetail('+row.id+')" zg-access="pagemanager/getHtmlFolder">'+row.filename+'</a>';
    //                            } else if(data == "doc"){
    //                                return '<input type="checkbox" value="'+ row.id +'" /><span class="doc-icon"></span><a href="#">'+row.filename+'.doc</a>';
    //                            } else if(data == "docx"){
    //                                return '<input type="checkbox" value="'+ row.id +'" /><span class="doc-icon"></span><a href="#">'+row.filename+'.docx</a>';
    //                            } else if(data == "pdf"){
    //                                return '<input type="checkbox" value="'+ row.id +'" /><span class="pdf-icon"></span><a href="#">'+row.filename+'.pdf</a>';
    //                            } else if(data == "html"){
    //                                return '<input type="checkbox" value="'+ row.id +'" /><span class="html-icon"></span><a href="#">'+row.filename+'.html</a>';
    //                            }
    //                        },"fnCreatedCell": function (nTd, sData, oData, iRow, iCol) {
    //                        $compile(nTd)($scope);
    //                    },
    //                        "targets": 0
    //                    },
    //                    {
    //                        "render":function(data, type, row){
    //                           if(data==0&&row.suffix==""){
    //                                return '';
    //                            }else{
    //                                return getTime.bytesToSize(data);
    //                            }
    //                        },
    //                        "targets":1
    //                    },
    //                    {
    //                        "render":function(data, type, row){
    //                            return getTime.getLocalTime(data);
    //                        },
    //                        "targets":2
    //                    }
    //                ]
    //            });
    //            if(response.data.id){
    //                $scope.fatherid=response.data.id;
    //                $("#bread-crumbs").empty();
    //                var compileFn = $compile('<li><a href="javascript:void(0);" ng-click="backoff('+response.data.id+')"  class="front">返回上一页</a><span>|</span></li><li><span>全部文件</span><span>'+response.data.localPath+'</span></li>');
    //                var $dom = compileFn($scope);
    //                $("#bread-crumbs").append($dom);
    //            }else{
    //                $scope.fatherid="";
    //                $("#bread-crumbs").empty();
    //                var html='<li><a href="javascript:void(0)">全部文件</a></li>';
    //                $("#bread-crumbs").append(html);
    //            }
    //        }else{
    //            toastr.error(response.data.message);
    //        }
    //    },function errorCallback(response){
    //        toastr.error(response.data.message);
    //    });
    //}
});

//用户管理的控制器
app.controller('userCtrl', function ($scope, $http,$compile,$state,$sessionStorage,getStorage) {
    var user = angular.fromJson($sessionStorage.USER);
    $scope.user=user;
    var flag=$sessionStorage.CJGLYFLG;
    //表格加载
    $scope.loadTable=function(){
        $.fn.dataTable.ext.errMode = 'none';
        $('#userTable').DataTable({
            //"dom": '<"top"i>rt<"bottom"flp><"clear">',
            "destroy": true,
            "searching": true,
            "bAutoWidth": true, //是否自适应宽度
            "sPaginationType": "full_numbers",
            "serverSide": true,//开启服务器模式，使用服务器端处理配置datatable
            //"processing": true,//开启读取服务器数据时显示正在加载中……特别是大数据量的时候，开启此功能比较好
            "bPaginage": true,
            "bDeferRender":true,
            "ordering": false, // 禁止排序
            "bFilter" : true, //是否启动过滤、搜索功能
            "language": {
                "sProcessing": "加载中...",
                "sLengthMenu": "显示 _MENU_ 项结果",
                "sZeroRecords": "没有匹配结果",
                "sInfo": "显示第 _START_ 至 _END_ 项结果，共 _TOTAL_ 项",
                "sInfoEmpty": "显示第 0 至 0 项结果，共 0 项",
                "sInfoFiltered": "(由 _MAX_ 项结果过滤)",
                "sInfoPostFix": "",
                "sSearch": "过滤:",
                "sEmptyTable": "表中数据为空",
                "sLoadingRecords": "载入中...",
                "sInfoThousands": ",",
                "oPaginate": {
                    "sFirst": "首页",
                    "sPrevious": "上页",
                    "sNext": "下页",
                    "sLast": "末页"
                },
                "oAria": {
                    "sSortAscending": ": 以升序排列此列",
                    "sSortDescending": ": 以降序排列此列"
                }
            },
            "fnPreDrawCallback": function( oSettings ) {
                $('.dataTables_filter input').attr({'name':'search','placeholder': '请输入用户名称'});//提示
            },
            "ajax":{
                "url":Url+'users/getAllUserByTenanid?tenanid='+user.tenanid+'&flag='+flag+'',
                "headers":{
                    "Authorization":token
                },
                "xhrFields": {
                    "withCredentials": true
                },
                error: function(){
                    $state.go("403");
                }
            },
            "columns": [
                {
                    "data": "id",
                    "render": function (data, type, full, meta) {
                        return '<input type="radio"   value="' + data + '" name="user"/>';
                    },
                },
                {"data": "tenanid"},
                {"data": "username"},
                {"data": "sex"},
                {"data": "phone"},
                {"data": "address"},
                {"data": "enable"},
                {"data": "enable"},
            ],
            "columnDefs": [
                {
                    "render": function (data, type, row) {
                        if (data == 1) {
                            return "女";
                        } else {
                            return "男";
                        }
                    },
                    "targets":3
                },
                {
                    "render": function (data, type, row) {
                        if (data == 1) {
                            return "冻结";
                        } else {
                            return "正常";
                        }
                    },
                    "targets": 6
                },
                {
                    "render": function (data, type, row) {
                        if (data == 1) {
                            return '<button type="button" class="btn btn-info" ng-click="updateState(' + row.id + ')" zg-access="users/updatestate">恢复</button>';
                        } else {
                            return '<button type="button" class="btn btn-danger" ng-click="updateState(' + row.id + ')" zg-access="users/updatestate">冻结</button>';
                        }
                    },"fnCreatedCell": function (nTd, sData, oData, iRow, iCol) {
                    $compile(nTd)($scope);
                },
                    "targets": 7
                },
            ],
        });
    };
    $(document).ready(function () {
        $scope.loadTable();
        getStorage.newStorage();
        $("#select option:eq(1)").remove()
    });
    //分配角色的弹框
    $scope.allotRole = function () {
        var ipts = $("#userTable :radio:checked").val();
        if (ipts) {
            $("#selectRole").modal("show");
            //获取该租户和用户下的所有角色
            $http({
                method:'post',
                url:Url+'userrole/getAllRoleByTenanid?tenanid='+user.tenanid+'',
                withCredentials:true,
                headers:{
                    Authorization:token
                },
                data:{userid:ipts},
            }).then(function successCallback(response) {
                if(response.data.code==0){
                    $scope.roleList=response.data.data;
                }
            });
        }else{
            toastr.warning('请选择一条数据');
        }
    };
    //保存分配角色
    $scope.saveUserRoles=function(){
        var ipts = $("#userTable :radio:checked").val();
        var roles = $("#boxRoleForm :checkbox:checked");
        var arr=[];
        roles.each(function(){arr.push($(this).val());});
        $http({
            method:'post',
            url:Url+'userrole/addRole',
            withCredentials:true,
            headers:{
                Authorization:token
            },
            data:{roleIdsArray:arr,userid:ipts}
        }).then(function successCallback(response) {
            if(response.data.code==0){
                toastr.success(response.data.message);
                $scope.loadTable();
                $("#selectRole").modal("hide");
            }
        },function errorCallback(response){
            toastr.error(response.data.message);
        });

    };
    //添加用户的弹框
    $scope.addUser=function(){
        $("#user").modal('show');
        $http({
            method: 'post',
            url:Url+'tenans/getAllTenan?id='+user.tenanid+'&flag='+flag+'',
            withCredentials:true,
            headers:{
                Authorization:token
            }
        }).then(function successCallback(response) {
                $scope.tenans=[];
                $.each(response.data.data,function(i,el){
                    $scope.tenans.push({
                       tenanname: el.tenanname,
                       id: el.id
                    });
                });
                $scope.tenanid= $scope.tenans[0].id;
        },function errorCallback(response){
            toastr.error(response.data.message);
        });
        $scope.sexList= [
            {value: "0", sex : "男"},
            {value: "1", sex : "女"}
        ];
        $scope.sex=$scope.sexList[0].value;
}
    //确定新增用户
    $scope.addSure = function () {
        var tenanid = $scope.tenanid;
        var username = $scope.username;
        var password =$scope.password;
        var email =$scope.email;
        var sex =$scope.sex;
        var phone =$scope.phone;
        var address =$scope.address;
        //验证租户ID
        if(tenanid == undefined || tenanid == null || tenanid==""){
            return toastr.error('租户ID不能为空');
        }else if(!(/^[0-9]{1,5}$/.test(tenanid))){
            return toastr.error('租户ID输入不正确，请重新输入');
        }
        //验证用户名
        if(username == undefined || username == null || username==""){
            return toastr.error('用户名不能为空');
        }
        //验证密码
        if(password == "" || password == undefined || password == null){
            return toastr.error('密码不能为空');
        } else if(!(/^[a-zA-Z0-9]{4,10}$/.test(password))){
            return toastr.error("密码格式不正确，请重新输入");
        }
        //验证手机号
        if(phone == "" || phone == undefined || phone == null){
            return toastr.error('手机号不能为空');
        }else if(!(/^1[34578]\d{9}$/.test(phone))){
            return toastr.error("手机号码有误，请重新输入");
        }
        //验证性别
        if(sex == "" || sex == undefined || sex == null){
            return toastr.error('请选择性别');
        }
        //验证邮箱
        if(email == "" || email == undefined || email == null){
            return toastr.error('邮箱不能为空');
        }else if(!(/^[a-zA-Z0-9_-]+@([a-zA-Z0-9]+\.)+(com|cn|net|org)$/.test(email))){
            return toastr.error("邮箱格式不正确，请重新输入");
        }
        if(address == "" || address == undefined || address == null){
            return toastr.error('地址不能为空');
        }
        $http( {
            method: 'post',
            url:Url+'users/add',
            withCredentials:true,
            headers:{
                Authorization:token
            },
            data:{username:username,password:password,tenanid:tenanid,sex:sex,phone:phone,address:address,email:email}
        }).then(function successCallback(response) {
            if(response.data.code==0){
                toastr.success(response.data.message);
                $scope.username="";
                $scope.password="";
                $scope.email="";
                $scope.sex="";
                $scope.phone="";
                $scope.address="";
                $scope.loadTable();
                $("#user").modal('hide');
            }else{
                toastr.error(response.data.message);
            }
        },function errorCallback(response){
            toastr.error(response.data.message);
        });
    };
    //删除用户
    $scope.deleteUser=function(){
        var ipts = $(":radio:checked").val();
        if (ipts)
        {
            $("#deleteSure").modal("show");
            $scope.sureDelete=function(){
                $http( {
                    method: 'post',
                    url:Url+'users/delete',
                    withCredentials:true,
                    headers:{
                        Authorization:token
                    },
                    data:{id:ipts}
                }).then(function successCallback(response) {
                    if(response.data.code==0){
                        toastr.success(response.data.message);
                        $scope.loadTable();
                        $("#deleteSure").modal("hide");
                    }else{
                        toastr.error(response.data.message);
                    }
                },function errorCallback(response){
                    toastr.error(response.data.message);
                });
            };

        }else{
            toastr.warning('请选择一条数据');
        }

    };
    //设置用户状态
    $scope.updateState=function(id){
        $http( {
            method: 'post',
            url:Url+'users/updatestate',
            withCredentials:true,
            headers:{
                Authorization:token
            },
            data:{id:id},
        }).then(function successCallback(response) {
            if(response.data.code==0){
                toastr.success(response.data.message);
                $scope.loadTable();
            }else{
                toastr.error(response.data.message);
            }
        },function errorCallback(response){
            toastr.error(response.data.message);
        });
    };
});

//角色管理的控制器
app.controller('roleCtrl',function ($scope, $http,$rootScope,$state,$sessionStorage,$ocLazyLoad,getStorage){
    $ocLazyLoad.load('../../lib/zTree/metroStyle/metroStyle.css');
    $ocLazyLoad.load('../../lib/zTree/jquery.ztree.excheck.min.js');
    var user = angular.fromJson($sessionStorage.USER);
    $scope.user=user;
    var flag=$sessionStorage.CJGLYFLG;
    $scope.loadTable=function(){
        $.fn.dataTable.ext.errMode = 'none';
        $('#roleTable').dataTable({
            "destroy": true,
            "searching": true,
            "search":true,
            "searchable":true,
            "bAutoWidth": true, //是否自适应宽度
            "sPaginationType": "full_numbers",
            "serverSide": true,//开启服务器模式，使用服务器端处理配置datatable
            "processing": false,//开启读取服务器数据时显示正在加载中……特别是大数据量的时候，开启此功能比较好
            "bPaginage": true,
            "ordering": false, // 禁止排序
            "bDeferRender":true,
            "bFilter" : true, //是否启动过滤、搜索功能
            "language": {
                "sProcessing": "处理中...",
                "sLengthMenu": "显示 _MENU_ 项结果",
                "sZeroRecords": "没有匹配结果",
                "sInfo": "显示第 _START_ 至 _END_ 项结果，共 _TOTAL_ 项",
                "sInfoEmpty": "显示第 0 至 0 项结果，共 0 项",
                "sInfoFiltered": "(由 _MAX_ 项结果过滤)",
                "sInfoPostFix": "",
                "sSearch": "过滤:",
                "sUrl": "",
                "sEmptyTable": "表中数据为空",
                "sLoadingRecords": "载入中...",
                "sInfoThousands": ",",
                "oPaginate": {
                    "sFirst": "首页",
                    "sPrevious": "上页",
                    "sNext": "下页",
                    "sLast": "末页"
                },
                "oAria": {
                    "sSortAscending": ": 以升序排列此列",
                    "sSortDescending": ": 以降序排列此列"
                }
            },
            "fnPreDrawCallback": function( oSettings ) {
                $('.dataTables_filter input').attr({'name':'search','placeholder': '请输入角色名称'});//提示
            },
            "ajax":{
                "url":Url+'roles/getRolesByTenanId?tenanid='+user.tenanid+'&flag='+flag+'',
                "headers":{
                    "Authorization":token
                },
                "xhrFields": {
                    "withCredentials": true
                },
                error: function(){
                    $state.go("403");
                }
            },

            "columns": [
                {
                    "data": "id",
                    "orderable": false,
                    "render": function (data, type, full, meta) {
                        return '<input type="radio"   value="' + data + '" name="role"/>';
                    },
                    "bSortable": false
                },
                {"data": "id"},
                {"data": "roledesc"},
            ],
        });
    };
    //表格展示
    $(document).ready(function(){
        $scope.loadTable();
        getStorage.newStorage();
    });

    //权限分配的弹框
    var roleId;
    $scope.setResources=function(){
        var ipts = $("#roleTable :radio:checked").val();
        roleId=ipts;
        if (ipts) {
            //展示权限列表
            var setting = {
                check: {
                    enable: true,
                    chkboxType:  { "Y" : "p", "N" : "s" }
                },
                data: {
                    simpleData: {
                        enable: true,
                        idKey: "id",
                        pIdKey: "Pid",
                    }
                }
            };
            $http( {
                method: 'post',
                url:Url+"roles/getAllResourceWithTenanId",
                withCredentials:true,
                headers:{
                    Authorization:token
                },
                data:{tenanid:user.tenanid,roleid:ipts},
            }).then(function successCallback(response) {
                if(response.data.code==0){
                    $.fn.zTree.init($("#treeDemo"), setting, response.data.data);
                    var zTree = $.fn.zTree.getZTreeObj("treeDemo");
                    zTree.expandAll(true);
                    $('#selectResources').modal("show");
                    // 获取树对象
                    var treeObj = $.fn.zTree.getZTreeObj("treeDemo");
                    /** 获取所有树节点 */
                    var nodes = treeObj.transformToArray(treeObj.getNodes());
                    // 遍历树节点设置树节点为选中
                    for (var k = 0, length_3 = nodes.length; k < length_3; k++) {
                        if (nodes[k].flg==1) {
                            zTree.checkNode(nodes[k], true, true)
                        }
                    }
                }else{
                    toastr.error(response.data.message);
                }
            },function errorCallback(response){
                toastr.error(response.data.message);
            });
        }else{
            toastr.warning('请选择一条数据');
        }

    };
    //保存权限分配
    $scope.saveResources=function(){
        var ipts = $("#roleTable :radio:checked").val();
        var zTree = $.fn.zTree.getZTreeObj("treeDemo"),
            checkNode= zTree.getCheckedNodes(true);
        var ids = new Array();
        for(var i=0;i<checkNode.length;i++){
            ids.push(checkNode[i].id);
        }
        $http( {
            method:'post',
            url:Url+'roles/saveRoleResources',
            withCredentials:true,
            headers:{
                Authorization:token
            },
            data:{roldid:ipts,resourcresid:ids}
        }).then(function successCallback(response) {
            if(response.data.code==0){
                toastr.success(response.data.message);
                $scope.loadTable();
                $("#selectResources").modal("hide");
            }else{
                toastr.error(response.data.message);
                $("#selectResources").modal("hide");
            }
        },function errorCallback(response){
            toastr.error(response.data.message);
        });
    };

    //新增角色的表单
    $scope.sureRole=function(){
        if(angular.isUndefined($scope.roledesc)){
            $scope.roledesc="";
            toastr.error("角色名称不能为空");
        };
        if( $scope.roledesc!==""){
            $http({
                method: 'post',
                url:Url+'roles/add',
                withCredentials:true,
                headers:{
                    Authorization:token
                },
                data:{roledesc:$scope.roledesc,tenanid:user.tenanid}
            }).then(function successCallback(response) {
                if(response.data.code==0){
                    toastr.success(response.data.message);
                    $scope.loadTable();
                    $scope.roledesc="";
                    $('#addForm').modal('hide');
                }else{
                    toastr.error(response.data.message);
                }
            },function errorCallback(response){
                toastr.error(response.data.message);
            });
        }
    };
    //删除角色
    $scope.deleteRole=function(){
        var ipts = $(":radio:checked").val();
        if (ipts) {
            $("#deleteSure").modal("show");
            $scope.sureDelete=function(){
                $http( {
                    method: 'post',
                    url:Url+'roles/delete',
                    withCredentials:true,
                    headers:{
                        Authorization:token
                    },
                    data:{id:ipts}
                }).then(function successCallback(response) {
                    if(response.data.code==0){
                        toastr.success(response.data.message);
                        $scope.loadTable();
                        $("#deleteSure").modal("hide");
                    }else{
                        toastr.error(response.data.message);
                    }
                },function errorCallback(response){
                    // console.log(response.data)
                });
            }
        }else{
            toastr.warning('请选择一条数据');
        }
    };
});

//权限管理的控制器
app.controller('resourcesCtrl', function ($scope, $http, $compile,$state,$sessionStorage,getStorage) {
    var user = angular.fromJson($sessionStorage.USER);
    $scope.user=user;
    var flag=$sessionStorage.CJGLYFLG;
    //表格展示
    $scope.loadTable=function(){
        $.fn.dataTable.ext.errMode = 'none';
        $('#resourcesTable').dataTable({
            "destroy": true,
            "searching": true,
            "search":true,
            "searchable":true,
            "bAutoWidth": true, //是否自适应宽度
            "sPaginationType": "full_numbers",
            "serverSide": true,//开启服务器模式，使用服务器端处理配置datatable
            "processing": false,//开启读取服务器数据时显示正在加载中……特别是大数据量的时候，开启此功能比较好
            "bPaginage": true,
            "bDeferRender":true,
            "ordering":false,
            "bFilter" : true, //是否启动过滤、搜索功能
            "language": {
                "sProcessing": "处理中...",
                "sLengthMenu": "显示 _MENU_ 项结果",
                "sZeroRecords": "没有匹配结果",
                "sInfo": "显示第 _START_ 至 _END_ 项结果，共 _TOTAL_ 项",
                "sInfoEmpty": "显示第 0 至 0 项结果，共 0 项",
                "sInfoFiltered": "(由 _MAX_ 项结果过滤)",
                "sInfoPostFix": "",
                "sSearch": "过滤:",
                "sUrl": "",
                "sEmptyTable": "表中数据为空",
                "sLoadingRecords": "载入中...",
                "sInfoThousands": ",",
                "oPaginate": {
                    "sFirst": "首页",
                    "sPrevious": "上页",
                    "sNext": "下页",
                    "sLast": "末页"
                },
                "oAria": {
                    "sSortAscending": ": 以升序排列此列",
                    "sSortDescending": ": 以降序排列此列"
                }
            },
            "fnPreDrawCallback": function( oSettings ) {
                $('.dataTables_filter input').attr({'name':'search','placeholder': '请输入权限名称'});//提示
            },
            "ajax":{
                "url":Url+'resources/getResourcesListByUserid?userid='+user.userid+'&flag='+flag+'',
                "headers":{
                    "Authorization":token
                },
                "xhrFields": {
                    "withCredentials": true
                },
                error: function(){
                    $state.go("403");
                }
            },
            "columns": [
                {
                    "data": "id",
                    "bSortable": false,
                    "orderable": false,
                    "render": function (data, type, full, meta) {
                        return '<input type="checkbox"   value="' + data + '" />';
                    },
                },
                {"data": "id"},
                {"data": "name"},
                {"data": "resurl"},
            ],
            "columnDefs": [
                {
                    "data": "type",
                    "orderable": false,
                    "render": function (data, type, row) {
                        if (data == 0) {
                            return "一级菜单";
                        } else if(data==1){
                            return "二级菜单";
                        }else{
                            return "按钮"
                        }
                    },
                    "targets":4
                }

            ],
        });
    };
    $(document).ready(function(){
        $scope.loadTable();
        getStorage.newStorage();
    });
    //新增权限
    //$scope.addLimit=function(){
    //    $("#addForm").modal("show");
    //}
    //删除权限
    $scope.deleteResources=function(){
        var ipts = $(":checkbox:checked");
        var arr=[];
        ipts.each(function(){
            arr.push($(this).val());
        });
        if (arr.length<1) {
            toastr.warning('请选择一条数据');
        }else{
            $("#deleteSure").modal("show");
            $scope.sureDelete=function(){
                $http( {
                    method: 'post',
                    url:Url+'resources/logicDelete',
                    withCredentials:true,
                    headers:{
                        Authorization:token
                    },
                    data:{resourcesid:arr,userid:user.userid}
                }).then(function successCallback(response) {
                    if(response.data.code==0){
                        toastr.success(response.data.message);
                        $scope.loadTable();
                        $("#deleteSure").modal("hide");
                    }
                },function errorCallback(response){
                    if(!response.data.code==0){
                        toastr.error(response.data.message);
                    }
                });
            };
        }
    };
});
//租户管理的控制器
app.controller('tenanCtrl', function ($scope,$http,$compile,$state,$sessionStorage,getStorage,getTime) {
    var user = angular.fromJson($sessionStorage.USER);
    $scope.user=user;
    var flag=$sessionStorage.CJGLYFLG;
    //表格展示
    $scope.loadTable=function(){
        $.fn.dataTable.ext.errMode = 'none';
        $('#tenanTable').dataTable({
            //"dom": '<"top"i>rt<"bottom"flp><"clear">',
            "destroy": true,
            "searching": true,
            "bAutoWidth": true, //是否自适应宽度
            "sPaginationType": "full_numbers",
            "serverSide": true,//开启服务器模式，使用服务器端处理配置datatable
            //"processing": true,//开启读取服务器数据时显示正在加载中……特别是大数据量的时候，开启此功能比较好
            "bPaginage": true,
            "ordering":false,
            "bDeferRender":true,
            "bFilter" : true, //是否启动过滤、搜索功能
            "language": {
                "sProcessing": "加载中...",
                "sLengthMenu": "显示 _MENU_ 项结果",
                "sZeroRecords": "没有匹配结果",
                "sInfo": "显示第 _START_ 至 _END_ 项结果，共 _TOTAL_ 项",
                "sInfoEmpty": "显示第 0 至 0 项结果，共 0 项",
                "sInfoFiltered": "(由 _MAX_ 项结果过滤)",
                "sInfoPostFix": "",
                "sSearch": "过滤:",
                "sEmptyTable": "表中数据为空",
                "sLoadingRecords": "载入中...",
                "sInfoThousands": ",",
                "oPaginate": {
                    "sFirst": "首页",
                    "sPrevious": "上页",
                    "sNext": "下页",
                    "sLast": "末页"
                },
                "oAria": {
                    "sSortAscending": ": 以升序排列此列",
                    "sSortDescending": ": 以降序排列此列"
                }
            },
            "fnPreDrawCallback": function( oSettings ) {
                $('.dataTables_filter input').attr({'name':'search','placeholder': '请输入租户名称'});//提示
            },
            "ajax":{
                "url":Url+'tenans/getAllTenan?id='+user.tenanid+'&flag='+flag+'',
                "headers":{
                    "Authorization":token
                },
                "xhrFields": {
                    "withCredentials": true
                },
                error: function(){
                    $state.go("403");
                }
            },

            "columns": [
                {
                    "data": "id",
                    "orderable": false,
                    "render": function (data, type, full, meta) {
                        return '<input type="radio"   value="' + data + '" name="tenan"/>';
                    },
                    "bSortable": false
                },
                {"data": "id"},
                {"data": "tenanname"},
                {"data": "tenancode"},
                {"data": "storage"},
            ],
            "columnDefs":[
                {
                    "render":function(data, type, row){
                        if(data==0&&row.suffix==""){
                            return '';
                        }else{
                            return getTime.bytesToSize(data);
                        }
                    },
                    "targets":4
                },
            ],
        });
    };
    $(document).ready(function(){
        $scope.loadTable();
        getStorage.newStorage();
    });
    //设置属性弹框显示
    $scope.setCode=function(){
        var ipts = $("#tenanTable :radio:checked").val();
        $(".text-center tbody").empty();
        if(ipts==""||ipts==undefined){
            toastr.warning("请选择一条数据");
        }else{
            $http({
                method: 'get',
                url:Url+'tenanproperty/gettenanProperty?tenanid='+ipts+'',
                withCredentials:true,
                headers:{
                    Authorization:token
                },
            }).then(function successCallback(response) {
                if(response.data.code==0){
                    if(flag==1){
                        for(var key in response.data.data){
                            var arr=response.data.data[key].split('|');
                            var value=arr[0];
                            var flg=arr[1];
                            if(value==undefined||value==""){
                                value="";
                            }
                            var tr='<tr><td>'+key+'</td><td><input type="text" class="form-control" value="'+value+'" placeholder="请输入属性值"></td></tr>';
                            $(".text-center tbody").append(tr);
                            $("#set").modal("show");
                        }
                    }else{
                        for(var key in response.data.data){
                            var arr=response.data.data[key].split('|');
                            var value=arr[0];
                            var flg=arr[1];
                            if(value==undefined||value==""){
                                value="";
                            }
                            if(flg==2){
                                var tr='<tr><td>'+key+'</td><td><input type="text" class="form-control" value="'+value+'" readonly="readonly"></td></tr>';
                            }else if(flg==3){
                                var tr='<tr><td>'+key+'</td><td><input type="text" class="form-control" value="'+value+'" placeholder="请输入公司属性值"></td></tr>';
                            }else{
                                var tr="";
                            }
                            $(".text-center tbody").append(tr);
                            $("#set").modal("show");
                        }
                    }
                }else{
                    toastr.error(response.data.message);
                }
            },function errorCallback(response){
                toastr.error(response.data.message);
            });
        }

    };
    //保存公司属性
    $scope.sureCode=function(){
        var id= $("#tenanTable :radio:checked").val();
        var myData = [];//声明一个数组，用于存放table的值
        var myInput= [];//声明一个数组，用于存放input的值
        for (var i = 0,tdlen= $("#codeTable tbody tr").length; i < tdlen; i++) {
            td = $("#codeTable tbody tr").eq(i).find("td:first").html();
            myData.push(td);//取出所有属性名称
            input=$("#codeTable tbody tr").eq(i).find("input").val();
            if(input==undefined){
                input.value="";
            }
            myInput.push(input);//取出所有input值
        }
        var obj={};//拼接成对象key：value
        for(var i=0;i<myData.length;i++){
            obj[myData[i]]=myInput[i]
        }
        var json=JSON.stringify(obj);
        $http({
            method: 'post',
            url:Url+'tenanproperty/saveTenanProperty',
            withCredentials:true,
            headers:{
                Authorization:token
            },
            data:{property:json,tenanid:id}
        }).then(function successCallback(response) {
            if(response.data.code==0){
                toastr.success(response.data.message);
                $scope.loadTable();
                $('#set').modal('hide');
            }else{
                toastr.error(response.data.message);
            }
        },function errorCallback(response){
            toastr.error(response.data.message);
        });
    };
    //新增公司的表单
    $scope.sureTenan=function(){
        var tenanname=$scope.tenanname;
        var tenancode=$scope.tenancode;
        var storage=$scope.storage;
        if(tenanname == "" || tenanname == undefined || tenanname == null){
            return toastr.error('租户名称不能为空');
        };
        if(tenancode == "" || tenancode == undefined || tenancode == null){
            return toastr.error('租户CODE不能为空');
        } else if(!(/^[a-zA-Z0-9]{4,10}$/.test(tenancode))){
            return toastr.error("租户格式不正确，请重新输入");
        };
        if(storage == "" || storage == undefined || storage == null){
            return toastr.error('存储空间不能为空');
        } else if(storage<0){
            return toastr.error("存储空间必须大于0，请重新输入");
        };
        $http({
            method: 'post',
            url:Url+'tenans/addTenan',
            withCredentials:true,
            headers:{
                Authorization:token
            },
            data:{tenanname:tenanname,tenancode:tenancode,storage:storage,userid:user.userid}
        }).then(function successCallback(response) {
            if(response.data.code==0){
                toastr.success(response.data.message);
                $scope.loadTable();
                $scope.tenanname="";
                $scope.tenancode="";
                $scope.storage="";
                $('#addForm').modal('hide');
            }else{
                toastr.error(response.data.message);
            }
        },function errorCallback(response){
            toastr.error(response.data.message);
        });
    };
    //删除租户
    $scope.deleteTenan=function(){
        var ipts = $(":radio:checked").val();
        if (ipts.length<1) {
            toastr.warning('请选择一条数据');
        }else{
            $("#deleteSure").modal("show");
            $scope.sureDelete=function(){
                $http( {
                    method: 'post',
                    url:Url+'tenans/deleteTenan',
                    withCredentials:true,
                    headers:{
                        Authorization:token
                    },
                    data:{id:ipts}
                }).then(function successCallback(response) {
                    if(response.data.code==0){
                        toastr.success(response.data.message);
                        $scope.loadTable();
                        $("#deleteSure").modal("hide");
                    }else{
                        toastr.error(response.data.message);
                    }
                },function errorCallback(response){
                    // console.log(response.data)
                });
            };

        }
    };

});
//个人信息的控制器
app.controller('personinfoCtrl',function ($scope, $http,$state,$sessionStorage,getStorage) {
    var user = angular.fromJson($sessionStorage.USER);
    var flag=$sessionStorage.CJGLYFLG;
    $scope.user=user;
    $http( {
        method: 'get',
        url:Url+'users/getUserData?id='+user.userid+'&flag='+flag+'',
        withCredentials:true,
        headers:{
            Authorization:token
        }
    }).then(function successCallback(response) {
        if(response.data.code==0){
            $scope.personinfo=response.data.data[0];
            getStorage.newStorage();
        }else{
            toastr.error(response.data.message);
        }
    },function errorCallback(response){
        toastr.error(response.data.message);
    });
    //确定修改个人信息
    $scope.sureChange=function(){
        var phone = $scope.personinfo.phone;
        var email = $scope.personinfo.email;
        var address = $scope.personinfo.address;
        //验证手机号
        if(phone == "" || phone == undefined || phone == null){
            return toastr.error('手机号不能为空');
        }else if(!(/^1[34578]\d{9}$/.test(phone))){
            return toastr.error("手机号码有误，请重新输入");
        }
        //验证邮箱
        if(email == "" || email == undefined || email == null){
            return toastr.error('邮箱不能为空');
        }else if(!(/^[a-zA-Z0-9_-]+@([a-zA-Z0-9]+\.)+(com|cn|net|org)$/.test(email))){
            return toastr.error("邮箱格式不正确，请重新输入");
        }
        if(address == "" || address == undefined || address == null){
            return toastr.error('地址不能为空');
        }
        $http( {
            method: 'post',
            url:Url+'users/saveUserData',
            withCredentials:true,
            headers:{
                Authorization:token
            },
            data:{phone:phone,email:email,address:address,id:user.userid}
        }).then(function successCallback(response) {
            if(response.data.code==0){
                toastr.success(response.data.message);
            }else{
                toastr.error(response.data.message);
            }
        },function errorCallback(response){
            toastr.error(response.data.message);
        });

    }
    //取消修改个人信息
    $scope.cancelChange=function(){
        $window.location.reload();
    }
});
//修改密码
app.controller('changepwdCtrl',function ($scope, $http,$state,$sessionStorage,getStorage) {
    var user = angular.fromJson($sessionStorage.USER);
    $scope.user=user;
    var flag=$sessionStorage.CJGLYFLG;
    getStorage.newStorage();
    $scope.change=function(){
        var npwd= $scope.npwd;
        if(angular.isUndefined($scope.opwd)){
            $scope.opwd="";
        }
        if(angular.isUndefined($scope.npwd)){
            $scope.npwd="";
        }
        //验证密码
        if(npwd == "" || npwd == undefined || npwd == null){
            return toastr.error('密码不能为空');
        } else if(!(/^[a-zA-Z0-9]{4,10}$/.test(npwd))){
            return toastr.error("密码格式不正确，请重新输入");
        };
        $http( {
            method: 'post',
            url:Url+'users/updatePassword',
            withCredentials:true,
            headers:{
                Authorization:token
            },
            data:{opwd:$scope.opwd,npwd:$scope.npwd,id:user.userid}
        }).then(function successCallback(response) {
            if(response.data.code==0){
                toastr.success(response.data.message);
            }else{
                toastr.error(response.data.message);
            }
        },function errorCallback(response){
            toastr.error(response.data.message);
        });

    }

});
//登录控制器
app.controller('loginCtrl',function ($scope, $state,$sessionStorage,$http) {
        var cjglyflg=0;
        if(angular.isUndefined($scope.username)){
            $scope.username="";
        }
        if(angular.isUndefined($scope.password)){
            $scope.password="";
        }
        $scope.login=function(){
            $http( {
                method: 'post',
                url:Url+'login',
                withCredentials:true,
                headers:{
                    Authorization:token
                },
                data:{username:$scope.username,password:$scope.password}
            }).then(function successCallback(response) {
                if(response.data.code == 0) {
                    var user = response.data.data.user;
                    var role = response.data.data.role;
		            var resource = response.data.data.resource;
		            var resurl='403';
                    $scope.user=user;
                    token = response.data.data.token;
                    $http.defaults.headers.common.Authorization =token;
                    $sessionStorage.TOKEN = token;
		            $sessionStorage.PERMISSION = resource;
		       //超级管理员标识赋值
                    for(var n in role){
                        if(role[n].type == 1) {
                            cjglyflg = 1;
                            break;
			            }
                    }
                    //取得跳转页面
                    for(var m in resource){
                        if(resource[m].type == 1) {
                            resurl = resource[m].resurl.toString().substr(1);
                            break;
                        }
                    }
                    $sessionStorage.CJGLYFLG= cjglyflg;
                    $sessionStorage.USER = angular.toJson({
                        "userid":user.id,
                        "username":user.username,
                        "enable":user.enable,
                        "role":role,
                        "tenanid":user.tenanid
                    });
                   $state.go(resurl.toString());
                    toastr.info(response.data.message);
                } else {
                    toastr.error(response.data.message);
                    $state.go('login');
                }
            });
        }
    }
);
/**自定义服务，基于角色的访问控制*/
app.service("auth",function($http, $sessionStorage){
    return {
        // 是否有访问某url的权限
        isAccessUrl:function(url) {
            var urlPermissions=$sessionStorage.PERMISSION;//角色里的权限列表
            if ($sessionStorage.USER != null) {
               var flg = 0;
               for(var j in urlPermissions) {
                  if(url.toLowerCase() == urlPermissions[j].resurl.toLowerCase().substr(1)){
                       flg = 1;
                        break;
                    }
                }
                if(flg == 1) {
                    return true;
                }else{
                    return false;
                }
            }else if(url=="login") {
                return true;
            }else {
                return false;
            }
        }
    }
});
/**路由访问控制*/
app.run(function($rootScope,$state, auth, $sessionStorage,$http){
    $rootScope.$on('$stateChangeStart', function(event, toState) {
        var user = angular.fromJson($sessionStorage.USER);
        token = $sessionStorage.TOKEN;
	    cjglyflg = $sessionStorage.CJGLYFLG;
        // 路由访问控制
        if(toState.name != '403' && !auth.isAccessUrl(toState.name) && token == null) {
            var user = angular.fromJson($sessionStorage.USER);
            if(user == null) {
                $state.go("login");
            }
            event.preventDefault();
            $state.go("403");
        }
    });
});
/**元素级别的访问控制指令（控制元素的显示/不显示以及可用/不可用）*/
app.directive("zgAccess", function($sessionStorage,$http){
    return {
        restrict: 'A',
        compile: function(element, attr) {
            var urlPermission=$sessionStorage.PERMISSION; //角色权限对应关系
            //切换菜单
            //var aNav = $("nav ul.ul li");
            //var listNav = $('.l_v');
            //aNav.each(function(i,s){
            //    $(s).click(function(){
            //        $(this).addClass("active").siblings().removeClass("active");
            //        //i=i+1;
            //        //console.log(i)
            //        //$(".l_s0"+ (i+1) +"").css('display','block');
            //        $(".l_s0"+ (i+1) +"").css('display','block');
            //        $(".l_s0"+ (i+1)+"").siblings().css('display','none');
            //    });
            //});
            var strUrl=window.location.href;
            var arrUrl=strUrl.split("/");
            var strPage=arrUrl[arrUrl.length-1];
            if(strPage==="filemanager"||strPage==="video"){
                name=2;
            }else if(strPage==="pagemanager"){
                name=1;
            }else if(strPage==="recycle"){
                name=4;
            }else if(strPage == "userinfo" || strPage == "userpwd"){
                name=5;
            }else{
                name=3;
            }
            if(name != 5) {
                var arr=$("nav ul.ul li");
                var thisMenu=arr[name-1];
                $(thisMenu).addClass("active").siblings().removeClass("active");
                $(".l_s0"+ (name) +"").css('display','block');
            }else{
                $(".l_s05").css('display','block');
            }
            //左侧菜单样式
            var menu=$(".l_s0"+ (name) +" .box-ul li a");
            for(i=0;i<menu.length;i++){
                var cmenu = menu[i].getAttribute("zg-access");
                if(cmenu==strPage){
                    var clickedMenu=menu[i];
                    $(clickedMenu).addClass('menu_active').removeClass('text1');
                    $(clickedMenu).parent().siblings().addClass('text1').removeClass('menu_active');
                    var url=cmenu+1;
                    $(clickedMenu).find("img").attr("src",'img/'+url+'.png');
                }else{

                }
            }
            // 初始为不可见状态none，还有 禁用disbaled和可用ok，共三种状态
            var level = "none";
            if(attr && attr["zgAccessLevel"]) {
                level = attr["zgAccessLevel"];
            }
            switch(level) {
                case "none": element.hide(); break;
                case "disabled":
                    element.attr("disabled", "");
                    break;
            }
            // 获取元素权限
            var access = attr["zgAccess"];
            return function(scope, element) {
                // 判断用户有无权限
                for(var j in urlPermission ){
                    if("/"+access.toLowerCase() == urlPermission[j].resurl.toLowerCase()){
                            element.removeAttr("disabled");
                            element.show();
                    }
                }
            };
        }
    }
});
/**http监听器，监听系统整体的$http请求失败*/
app.factory("httpInterceptor",function($q, $injector,$state,$rootScope) {
    return {
        'request': function(config){
            $rootScope.loading = true;
            return $q.resolve(config);
        },
        'response': function(response){
            $rootScope.loading = false;
            return $q.resolve(response);
        },
        'requestError':function(rejection){
            $rootScope.loading = false;
            return $q.reject(rejection);
        },
        "responseError": function (response) {
            $rootScope.loading = false;
            if (response.status == 401) {
                $state.go("403");
                return $q.reject(response);
            }
            else if (response.status === 417) {
                $state.go("403");
                return $q.reject(response);
            }
            else if (response.status === 403) {
                $state.go("403");
                return $q.reject(response);
            }
        }
    }
});
